Radix Sort
📚 Radix Sort
-
Radix Sort is a non-comparison based integer sorting algorithm.
-
It sorts numbers digit by digit, starting from the least significant digit (LSD) to the most significant digit (MSD).
-
It uses a stable sub-sorting algorithm like Counting Sort at each digit position.
👉 Idea:
✅ Key Point: Radix sort is very fast when number of digits is small compared to number of elements.
🛠️ Algorithm for Radix Sort
-
Find the maximum number to know the number of digits.
-
Start from Least Significant Digit (LSD).
-
Use stable counting sort based on the current digit.
-
Repeat for every digit (unit place, ten place, hundred place, etc).
Example
Let's sort:
[170, 45, 75, 90, 802, 24, 2, 66]
🔢 Pass 1: Units Place
Buckets (0–9):
- 0 → 170, 90
- 1 → —
- 2 → 802, 2
- 3 → —
- 4 → 24
- 5 → 45, 75
- 6 → 66
- 7 → —
- 8 → —
- 9 → —
🔢 Pass 2: Tens Place
(Based on order after Pass 1: 170, 90, 802, 2, 24, 45, 75, 66)
- 0 → 802, 2
- 1 → —
- 2 → 24
- 3 → —
- 4 → 45
- 5 → —
- 6 → 66
- 7 → 170, 75
- 8 → —
- 9 → 90
🔢 Pass 3: Hundreds Place
(Based on order after Pass 2: 802, 2, 24, 45, 66, 170, 75, 90)
- 0 → 2, 24, 45, 66, 75, 90
- 1 → 170
- 2 → —
- 3 → —
- 4 → —
- 5 → —
- 6 → —
- 7 → —
- 8 → 802
- 9 → —
✅ Final Sorted Order:
Example ( University Question)
So we perform 3 passes (units, tens, hundreds)
Buckets (0–9):
- 1 → 21, 121
- 2 → 342
- 3 → 3
- 4 → 34, 44
- 5 → 65
New Order:
0 → 3
2 → 21, 121
3 → 34
4 → 342, 44
6 → 65
New Order:
3, 21, 121, 34, 342, 44, 65
🔢 Pass 3: Sort by Hundreds Place
Buckets:
- 0 → 3, 21, 34, 44, 65
- 1 → 121
- 3 → 342
3, 21, 34, 44, 65, 121, 342
📋 Algorithm
RADIX_SORT(arr, n)
📈 Complexity
| Feature | Details |
|---|---|
| Time Complexity | O(d*(n + k)) where d = number of digits, n = number of elements, k = base (usually 10) |
| Space Complexity | O(n + k) |
| Stable Sorting | ✅ Yes |
| Best for | Sorting integers, large number of elements with small digit size |
📌 Important Points:
-
Radix Sort does not compare elements.
-
It is stable.
-
Works best when range of numbers is not huge.
-
For larger digits or variable-length strings, Radix Sort with MSD is used.
C Program - Radix Sort
170 45 75 90 802 24 2 66
Original array: 170 45 75 90 802 24 2 66
170 90 802 2 24 45 75 66
802 2 24 45 66 170 75 90
2 24 45 66 75 90 170 802
Sorted array: 2 24 45 66 75 90 170 802
Comments
Post a Comment