Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Radix Sort in python #971

Open
wants to merge 2 commits into
base: master
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
51 changes: 51 additions & 0 deletions algorithms/ar-radsrt/python2/radix_sort.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,51 @@
# Function to get the maximum value in the list
def getMax(arr):
max_val = arr[0]
for i in arr:
if i > max_val:
max_val = i
return max_val

# Counting sort to sort elements based on the significant digit
def countingSort(arr, exp):
n = len(arr)
output = [0] * n # Output array to hold sorted elements
count = [0] * 10 # Initialize counting array (for base 10 digits)

# Store the count of occurrences
for i in range(n):
index = (arr[i] // exp) % 10
count[index] += 1

# Change count[i] so that count[i] contains the actual position
for i in range(1, 10):
count[i] += count[i - 1]

# Build the output array
i = n - 1
while i >= 0:
index = (arr[i] // exp) % 10
output[count[index] - 1] = arr[i]
count[index] -= 1
i -= 1

# Copy the output array to arr
for i in range(n):
arr[i] = output[i]

# Main function to implement Radix Sort
def radixSort(arr):
# Find the maximum number to determine the number of digits
max_val = getMax(arr)
# Do counting sort for every digit
exp = 1
while max_val // exp > 0:
countingSort(arr, exp)
exp *= 10

# Example usage
arr = [170, 45, 75, 90, 802, 24, 2, 66]
print("Original array:", arr)
radixSort(arr)
print("Sorted array:", arr)

Loading