1. Understand the Goal: The user wants a program that implements Radix Sort.
-
Identify the Key Concepts of Radix Sort:
- It's a non-comparative sorting algorithm.
- It processes digits (from least significant to most significant, or vice versa).
- It usually relies on a stable sorting subroutine (like Counting Sort) to sort based on individual digit positions.
-
Determine the Language: Python is a good default for readability and ease of understanding, but C++ or Java are also common for algorithmic demonstrations. I'll provide the solution in Python as it's widely accessible, but maybe include a C++ version or just stick to a clear Python explanation. Let's stick to Python for the primary example, as it's concise. Self-correction: The user didn't specify a language. I will provide Python code because it's pseudocode-like, but I should make sure the logic is clear.
-
Drafting the Algorithm (LSD Radix Sort):
- Input: An array of non-negative integers (handling negatives requires extra steps, usually by splitting or offsetting, but for a standard explanation, non-negative is best).
- Step 1: Find the maximum number to know the number of digits.
- Step 2: Iterate for every digit position (1s, 10s, 100s, etc.).
- Step 3: Inside the loop, perform a stable sort (Counting Sort) based on the current digit.
-
Refining the "Counting Sort" subroutine:
- Needs an
output array of the same size as the input.
- Needs a
count array of size 10 (base 10).
- Phase 1: Count occurrences of each digit.
- Phase 2: Cumulative sum of counts (to determine positions).
- Phase 3: Build the output array by iterating backwards (to maintain stability).
-
Writing the Code (Mental Draft):
def counting_sort(arr, exp):
n = len(arr)
output = [0] * n
count = [0] * 10
# Store count of occurrences
for i in range(n):
index = (arr[i] // exp) % 10
count[index] += 1
# Change count[i] so it contains actual position
for i in range(1, 10):
count[i] += count[i - 1]
# Build output array (reverse loop for stability)
for i in range(n - 1, -1, -1):
index = (arr[i] // exp) % 10
output[count[index] - 1] = arr[i]
count[index] -= 1
# Copy back to arr
for i in range(n):
arr[i] = output[i]
def radix_sort(arr):
max_val = max(arr)
exp = 1
while max_val // exp > 0:
counting_sort(arr, exp)
exp *= 10
-
Addressing Edge Cases:
- Empty array? The code handles it (loops won't run or don't matter).
- Negative numbers? Standard Radix Sort usually assumes non-negative. Adding negative support complicates the code significantly (need to separate negative/positive, reverse negatives, sort, merge). For a standard "implement radix sort" prompt, non-negative is the expected baseline unless specified otherwise. I will stick to non-negative integers for clarity but add a note about it.
-
Structuring the Output:
- Introduction: Briefly explain what Radix Sort is (LSD approach).
- Code: The Python implementation.
- Explanation: Walk through the steps (Finding Max, Counting Sort subroutine).
- Complexity Analysis: Time (O(d⋅(n+b))) and Space (O().
This implementation uses the Least Significant Digit (LSD) approach. It relies on Counting Sort as a subroutine to sort the numbers based on individual digit positions.
Python Implementation
def counting_sort(arr, exp1):
"""
A subroutine to do counting sort of arr[] according to
the digit represented by exp1.
"""
n = len(arr)
# The output array elements that will have sorted numbers
output = [0] * (n)
# Initialize count array as 0
# We use 10 buckets because we are working with decimal numbers (0-9)
count = [0] * (10)
# Store count of occurrences in count[]
for i in range(0, n):
index = (arr[i] // exp1)
count[index % 10] += 1
# Change count[i] so that count[i] now contains actual
# position of this digit in output array
for i in range(1, 10):
count[i] += count[i - 1]
# Build the output array
# We traverse backward to ensure the sort is Stable
i = n - 1
while i >= 0:
index = (arr[i] // exp1)
output[count[index % 10] - 1] = arr[i]
count[index % 10] -= 1
i -= 1
# Copy the output array to arr[], so that arr now
# contains sorted numbers according to current digit
i = 0
for i in range(0, len(arr)):
arr[i] = output[i]
def radix_sort(arr):
"""
The main function to that sorts arr[] of size n using Radix Sort
"""
if len(arr) == 0:
return
# Find the maximum number to know number of digits
max1 = max(arr)
# Do counting sort for every digit. Note that instead
# of passing digit number, exp is passed. exp is 10^i
# where i is current digit number
exp = 1
while max1 // exp > 0:
counting_sort(arr, exp)
exp *= 10
# --- Driver Code to Test ---
if __name__ == "__main__":
sample_data = [170, 45, 75, 90, 802, 24, 2, 66]
print("Original array:", sample_data)
radix_sort(sample_data)
print("Sorted array: ", sample_data)
How it Works
- Find the Maximum: First, we find the largest number in the list (e.g.,
802). This tells us how many digits we need to process (in this case, 3 digits).
- Digit by Digit: We sort the list three times:
- 1st Pass (Ones place): Sorts based on the last digit (0, 5, 5, 0, 2, 4, 2, 6).
- 2nd Pass (Tens place): Sorts based on the middle digit (7, 4, 7, 9, 0, 2, 0, 6).
- 3rd Pass (Hundreds place): Sorts based on the first digit (1, 0, 0, 0, 8, 0, 0, 0).
- Counting Sort Subroutine: Radix sort cannot use standard comparison sorts (like Quicksort) internally; it must use a stable sort. We use Counting Sort because it is stable (if two items have the same digit, they retain their relative order from the previous pass) and efficient for small ranges (digits 0-9).
Complexity Analysis
- Time Complexity: O(d⋅(n+b))
- n is the number of elements.
- b is the base (10 for decimal numbers).
- d is the number of digits in the maximum number.
- In practice, if the range of numbers is reasonable, this is effectively .