w3resource

Python: Sort a list of elements using Radix sort

Python Search and Sorting : Exercise-19 with Solution

Write a Python program to sort a list of elements using Radix sort.
According to Wikipedia "In computer science, radix sort is a non-comparative integer sorting algorithm that sorts data with integer keys by grouping keys by the individual digits which share the same significant position and value".


Sample Solution:

Python Code:

def radix_sort(nums):
    RADIX = 10
    placement = 1
    max_digit = max(nums)

    while placement < max_digit:
      buckets = [list() for _ in range( RADIX )]
      for i in nums:
        tmp = int((i / placement) % RADIX)
        buckets[tmp].append(i)
      a = 0
      for b in range( RADIX ):
        buck = buckets[b]
        for i in buck:
          nums[a] = i
          a += 1
      placement *= RADIX
    return nums
user_input = input("Input numbers separated by a comma:\n").strip()
nums = [int(item) for item in user_input.split(',')]
print(radix_sort(nums))

Sample Output:

Input numbers separated by a comma:
 15, 79, 25, 68, 37
[15, 25, 37, 68, 79]

Flowchart:

Flowchart: Python Data Structures and Algorithms: Sort a list of elements using Radix sort

Python Code Editor:

Contribute your code and comments through Disqus.

Previous: Write a Python program to sort a list of elements using Pancake sort.
Next: Write a Python program to sort a list of elements using Selection sort.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Become a Patron!

Follow us on Facebook and Twitter for latest update.

It will be nice if you may share this link in any developer community or anywhere else, from where other developers may find this content. Thanks.

https://198.211.115.131/python-exercises/data-structures-and-algorithms/python-search-and-sorting-exercise-19.php