How to Implement Radix Sort in Python

In this tutorial, we will learn how to program "How to Implement Radix Sort in Python". The objective is to implement radix sort. This tutorial will guide you step by step through the process of implementing radix sort effectively. By the end of this tutorial, you will have a solid understanding of how to use radix sort in Python, helping you strengthen your problem-solving abilities and improve your coding skills.

This topic is straightforward and easy to understand. By following the instructions provided, you will be able to complete it with ease. The program will guide you step by step through the process of implementing radix sort. So, let’s dive into the coding process!

Getting Started:

First you will have to download & install the Python IDLE's, here's the link for the Integrated Development And Learning Environment for Python https://www.python.org/downloads/.

Creating Main Function

This is the main function of the application. The following code will display a simple GUI in terminal console that will display program. To do this, simply copy and paste these blocks of code into the IDLE text editor.
  1. def radix_sort(alist, base=10):
  2.     if alist == []:
  3.         return []
  4.  
  5.     def key_factory(digit, base):
  6.         def key(alist, index):
  7.             return (alist[index] // (base ** digit)) % base
  8.         return key
  9.  
  10.     largest = max(alist)
  11.     exp = 0
  12.  
  13.     while base ** exp <= largest:
  14.         alist = counting_sort(alist, base - 1, key_factory(exp, base))
  15.         exp += 1
  16.  
  17.     return alist
  18.  
  19.  
  20. def counting_sort(alist, largest, key):
  21.     c = [0] * (largest + 1)
  22.  
  23.     for i in range(len(alist)):
  24.         c[key(alist, i)] += 1
  25.  
  26.     # Convert to cumulative count
  27.     c[0] -= 1
  28.     for i in range(1, largest + 1):
  29.         c[i] += c[i - 1]
  30.  
  31.     result = [None] * len(alist)
  32.  
  33.     for i in range(len(alist) - 1, -1, -1):
  34.         result[c[key(alist, i)]] = alist[i]
  35.         c[key(alist, i)] -= 1
  36.  
  37.     return result
  38.  
  39.  
  40. # MAIN LOOP
  41. while True:
  42.     print("\n============= Implement Radix Sort =============\n")
  43.  
  44.     # Input handling
  45.     try:
  46.         user_input = input("Enter non-negative integers (space-separated): ").strip()
  47.         if not user_input:
  48.             print("Input cannot be empty.")
  49.             continue
  50.  
  51.         alist = [int(x) for x in user_input.split()]
  52.  
  53.         if any(x < 0 for x in alist):
  54.             print("Radix sort only supports non-negative integers.")
  55.             continue
  56.  
  57.     except ValueError:
  58.         print("Invalid input. Please enter integers only.")
  59.         continue
  60.  
  61.     print(f"Original list: {alist}")
  62.  
  63.     # Perform sorting
  64.     sorted_list = radix_sort(alist)
  65.  
  66.     print(f"Sorted list:   {sorted_list}")
  67.  
  68.     # Try Again Option
  69.     opt = input("\nDo you want to try again? (yes/no): ").strip().lower()
  70.     if opt == 'no':
  71.         print("Exiting program...")
  72.         break
  73.     elif opt != 'yes':
  74.         print("Invalid choice. Exiting program...")
  75.         break

This Python program implements Radix Sort, a non-comparative sorting algorithm that sorts non-negative integers digit by digit using a stable Counting Sort as a subroutine. It processes numbers starting from the least significant digit to the most significant, grouping and ordering them based on each digit place. The program runs interactively, allowing users to input a list of non-negative integers, display the original list, and view the sorted result. It also includes input validation and a loop that lets users repeat the process or exit.

Output:

There you have it we successfully created How to Implement Radix Sort in Python. I hope that this simple tutorial help you to what you are looking for. For more updates and tutorials just kindly visit this site. Enjoy Coding!

More Tutorials for Python Language

Python Tutorials