๐ Radix Sort (with Running Time Analysis)
1๏ธโฃ Introduction
Radix Sort is a non-comparison-based sorting algorithm used for sorting numbers digit by digit.
๐น Idea
- Sort numbers based on individual digits
- Start from:
- Least Significant Digit (LSD) โ most common
- or Most Significant Digit (MSD)
It uses a stable sorting algorithm (like Counting Sort) as a subroutine.
2๏ธโฃ Working Principle
๐น Steps (LSD Method)
- Sort elements based on units place
- Then sort based on tens place
- Then hundreds place, and so on
- Continue until all digits are processed
โ Maintain stability at each step
3๏ธโฃ Algorithm (Radix Sort)
๐น Pseudocode
RadixSort(A, n):
max = maximum element in A
for exp = 1; max/exp > 0; exp = exp * 10:
CountingSort(A, n, exp)
๐น Counting Sort (for each digit)
CountingSort(A, n, exp):
create output array
create count[10] initialized to 0
for i = 0 to n-1:
index = (A[i] / exp) % 10
count[index]++
compute cumulative count
for i = n-1 to 0:
index = (A[i] / exp) % 10
output[count[index] - 1] = A[i]
count[index]--
copy output to A
4๏ธโฃ Example (Step-by-Step)
๐น Given Array:
A = [170, 45, 75, 90, 802, 24, 2, 66]
๐น Step 1: Sort by Units Place
[170, 90, 802, 2, 24, 45, 75, 66]
๐น Step 2: Sort by Tens Place
[802, 2, 24, 45, 66, 170, 75, 90]
๐น Step 3: Sort by Hundreds Place
[2, 24, 45, 66, 75, 90, 170, 802]
โ Final Sorted Array
5๏ธโฃ Running Time Analysis
๐น Let:
- n = number of elements
- d = number of digits
- k = range of digits (0โ9 โ k = 10)
๐น Time Complexity:
[
O(d \cdot (n + k))
]
Since k = 10 (constant):
[
O(d \cdot n)
]
6๏ธโฃ Time Complexity Cases
| Case | Complexity |
|---|---|
| Best Case | O(dn) |
| Average Case | O(dn) |
| Worst Case | O(dn) |
โ Same in all cases
7๏ธโฃ Space Complexity
- O(n + k)
- Requires extra memory for counting sort
8๏ธโฃ Characteristics of Radix Sort
โ Non-comparison-based
โ Stable sorting algorithm
โ Works on integers or fixed-length keys
โ Very fast for large datasets
9๏ธโฃ Advantages
- Faster than comparison sorts for large data
- Linear time complexity (for fixed digits)
- Stable sorting
๐ Disadvantages
- Extra memory required
- Not suitable for:
- Floating-point numbers (directly)
- Variable-length data
- Depends on digit count
1๏ธโฃ1๏ธโฃ Comparison with Other Sorting Algorithms
| Algorithm | Time Complexity | Type |
|---|---|---|
| Radix Sort | O(dn) | Non-comparison |
| Merge Sort | O(n log n) | Comparison |
| Quick Sort | O(n log n) avg | Comparison |
๐ Conclusion
Radix Sort is a highly efficient sorting algorithm for numbers with fixed digit lengths.
It sorts data digit by digit using a stable sorting method, achieving near-linear time complexity.
๐ Exam Tip
๐ Always include:
- Digit-wise sorting explanation
- Counting sort usage
- Time complexity formula
- Example
