Created
December 26, 2022 22:08
-
-
Save ZhouYang1993/fb4f4d496146c0e0b346fedea8731a99 to your computer and use it in GitHub Desktop.
Mastering Radix Sort in Python: A Visual Guide
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
def radix_sort(arr): | |
""" | |
Radix sort starting from the least significant digit(LSD) | |
:param arr: The list needs to be sorted | |
:return: A sorted list | |
""" | |
# Find the maximum number of digits in the list | |
max_digits = max([len(str(x)) for x in arr]) | |
# Set the base (radix) to 10 | |
base = 10 | |
# Create a list of bins to store the digits | |
bins = [[] for _ in range(base)] | |
# Iterate through each digit, starting with the least significant | |
for i in range(0, max_digits): | |
# Iterate through the elements in the list | |
for x in arr: | |
# Extract the i-th digit from the element | |
# (starting from the rightest digit) | |
digit = (x // base ** i) % base | |
# Add the element to the bin for the i-th digit | |
bins[digit].append(x) | |
# Combine the bins back into the list, starting with the elements in the 0 queue | |
arr = [x for queue in bins for x in queue] | |
# Clear the bins for the next iteration | |
bins = [[] for _ in range(base)] | |
return arr | |
# Test the function | |
print(radix_sort([38, 2, 100, 5, 276, 42])) | |
# Output: [2, 5, 38, 42, 100, 276] |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Thanks! Output of bins and arr on each iteration