Radix Sort in C++
1. What Is Radix Sort?
Radix Sort is a sorting algorithm that arranges numbers digit by digit rather than comparing complete numbers.
For example, when sorting decimal integers, Radix Sort processes:
- Units digit
- Tens digit
- Hundreds digit
- Thousands digit
It uses a stable sorting method, commonly Counting Sort, to arrange the numbers according to the current digit.
Example
Consider the following array:
arr = {170, 45, 75, 90, 802, 24, 2, 66}
After applying Radix Sort:
arr = {2, 24, 45, 66, 75, 90, 170, 802}
2. Why Is Radix Sort Needed?
Comparison-based algorithms such as Quick Sort and Merge Sort compare complete elements to determine their order.
Radix Sort takes another approach. It separates numbers into individual digits and sorts them using a stable sorting algorithm.
This can be efficient when sorting integers with a limited number of digits.
3. Types of Radix Sort
Radix Sort has two commonly discussed approaches.
1. LSD Radix Sort
LSD stands for Least Significant Digit.
It starts sorting from the rightmost digit and moves toward the leftmost digit.
Example: 472
Units = 2
Tens = 7
Hundreds = 4
LSD Radix Sort processes the units digit first, then the tens digit, and finally the hundreds digit.
2. MSD Radix Sort
MSD stands for Most Significant Digit.
It begins with the leftmost digit and processes progressively less significant digits.
Example: 472
Hundreds = 4
Tens = 7
Units = 2
4. How Does LSD Radix Sort Work?
LSD Radix Sort follows these steps:
- Find the maximum number in the array.
- Start with the units digit.
- Sort all numbers according to the current digit using a stable sort.
- Move to the tens digit.
- Repeat for hundreds, thousands, and other digit positions.
- Stop when all digit positions of the maximum number have been processed.
5. Understanding Digit Positions
In a decimal number system, each digit has a position value.
| Position | Place Value | Example in 538 |
|---|---|---|
| 1 | Units | 8 |
| 10 | Tens | 3 |
| 100 | Hundreds | 5 |
To extract a digit at a particular place value, we use:
digit = (number / place) % 10
For example, if number = 538:
Units:
(538 / 1) % 10 = 8
Tens:
(538 / 10) % 10 = 3
Hundreds:
(538 / 100) % 10 = 5
6. Step-by-Step Example of Radix Sort
Consider this array:
arr = {170, 45, 75, 90, 802, 24, 2, 66}
The maximum number is 802. Therefore, we need to process three digit positions.
Pass 1: Sort by Units Digit
Extract the units digit from every number:
| Number | Units Digit |
|---|---|
| 170 | 0 |
| 45 | 5 |
| 75 | 5 |
| 90 | 0 |
| 802 | 2 |
| 24 | 4 |
| 2 | 2 |
| 66 | 6 |
After stable sorting by units digit:
{170, 90, 802, 2, 24, 45, 75, 66}
Pass 2: Sort by Tens Digit
Now extract the tens digit from each number and perform another stable sort.
{802, 2, 24, 45, 66, 170, 75, 90}
Pass 3: Sort by Hundreds Digit
Finally, sort the array according to the hundreds digit.
{2, 24, 45, 66, 75, 90, 170, 802}
Final Sorted Array: 2 24 45 66 75 90 170 802
7. Why Is Stability Important in Radix Sort?
Stability means that elements with equal keys retain their original relative order.
Radix Sort depends on this property because each pass sorts only one digit. A later pass must not destroy the ordering established by an earlier pass.
Example
Consider these numbers after sorting by their units digit:
{21, 31, 42, 52}
When sorting by the tens digit, stable sorting preserves the relative order of numbers with the same tens digit.
8. Counting Sort for a Specific Digit
We use Counting Sort to sort numbers based on one digit position at a time.
The following function sorts the array according to the digit represented by exp.
void countingSort(vector<int>& arr, int exp) {
int n = arr.size();
vector<int> output(n);
int count[10] = {0};
// Count digit frequencies
for (int i = 0; i < n; i++) {
int digit = (arr[i] / exp) % 10;
count[digit]++;
}
// Calculate cumulative counts
for (int i = 1; i < 10; i++) {
count[i] += count[i - 1];
}
// Place elements from right to left
for (int i = n - 1; i >= 0; i--) {
int digit = (arr[i] / exp) % 10;
output[count[digit] - 1] = arr[i];
count[digit]--;
}
// Copy output back
for (int i = 0; i < n; i++) {
arr[i] = output[i];
}
}
Code Explanation
- exp: Represents the current digit position (1, 10, 100, and so on).
- count[10]: Stores the frequencies of digits from 0 to 9.
- digit: Extracts the digit using division and modulo.
- Cumulative count: Calculates the final positions of elements.
- Right-to-left traversal: Maintains stability.
- Output array: Temporarily stores the sorted elements.
9. Complete Radix Sort Algorithm
The complete algorithm repeatedly calls the digit-based Counting Sort function.
radixSort(arr):
find maximum element
exp = 1
while maximum / exp > 0:
countingSort(arr, exp)
exp = exp * 10
10. Complete C++ Program for Radix Sort
The following implementation sorts non-negative integers in ascending order.
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
void countingSort(vector<int>& arr, long long exp) {
int n = arr.size();
vector<int> output(n);
int count[10] = {0};
// Count digit frequencies
for (int i = 0; i < n; i++) {
int digit = (arr[i] / exp) % 10;
count[digit]++;
}
// Calculate cumulative counts
for (int i = 1; i < 10; i++) {
count[i] += count[i - 1];
}
// Stable placement from right to left
for (int i = n - 1; i >= 0; i--) {
int digit = (arr[i] / exp) % 10;
output[count[digit] - 1] = arr[i];
count[digit]--;
}
// Copy output to original array
for (int i = 0; i < n; i++) {
arr[i] = output[i];
}
}
void radixSort(vector<int>& arr) {
if (arr.empty()) {
return;
}
// Radix Sort implementation here supports
// non-negative integers only.
for (int x : arr) {
if (x < 0) {
cout << "Negative numbers are not supported";
return;
}
}
int maximum = *max_element(arr.begin(), arr.end());
// Sort by each digit position
for (long long exp = 1;
maximum / exp > 0;
exp *= 10) {
countingSort(arr, exp);
}
}
int main() {
vector<int> arr = {
170, 45, 75, 90, 802, 24, 2, 66
};
radixSort(arr);
cout << "Sorted Array: ";
for (int x : arr) {
cout << x << " ";
}
return 0;
}
Output
Sorted Array: 2 24 45 66 75 90 170 802
11. Understanding the Main Radix Sort Loop
for (long long exp = 1;
maximum / exp > 0;
exp *= 10) {
countingSort(arr, exp);
}
This loop processes every digit position.
| exp | Digit Position |
|---|---|
| 1 | Units |
| 10 | Tens |
| 100 | Hundreds |
| 1000 | Thousands |
The loop stops when the maximum number has no more digits at the current or any higher position.
12. Dry Run of Radix Sort
Input:
arr = {329, 457, 657, 839, 436, 720, 355}
Initial Array
{329, 457, 657, 839, 436, 720, 355}
Pass 1: Units Digit
{720, 355, 436, 457, 657, 329, 839}
Pass 2: Tens Digit
{720, 329, 436, 839, 355, 457, 657}
Pass 3: Hundreds Digit
{329, 355, 436, 457, 657, 720, 839}
Final Sorted Array: 329 355 436 457 657 720 839
13. Time Complexity of Radix Sort
Radix Sort processes d digit positions. For decimal numbers, each digit pass uses Counting Sort with a base of 10.
Each digit pass takes O(n + b) time, where:
- n: Number of elements.
- d: Maximum number of digits.
- b: Digit base, which is 10 for decimal numbers.
The total time complexity is:
O(d × (n + b))
For decimal integers, b = 10, so the complexity is commonly simplified to:
O(d × n)
| Case | Time Complexity |
|---|---|
| Best Case | O(d × (n + b)) |
| Average Case | O(d × (n + b)) |
| Worst Case | O(d × (n + b)) |
14. Space Complexity of Radix Sort
The implementation uses an output array of size n and a digit-count array of size b.
Therefore, its auxiliary space complexity is:
O(n + b)
For decimal Radix Sort, b is 10, so the extra space is commonly described as O(n).
15. Radix Sort Complexity Summary
| Property | Complexity or Value |
|---|---|
| Best Time | O(d × (n + b)) |
| Average Time | O(d × (n + b)) |
| Worst Time | O(d × (n + b)) |
| Auxiliary Space | O(n + b) |
| Stable | Yes, when stable digit sorting is used |
| Comparison-based | No |
| Digit Base | 10 for decimal implementation |
16. Advantages of Radix Sort
- Does not rely on comparisons between complete numbers.
- Can be efficient for integers with a limited number of digits.
- Can achieve linear time when the digit count and base are bounded.
- Can be stable when each digit pass uses a stable sorting algorithm.
- Works well with fixed-length integer keys.
17. Disadvantages of Radix Sort
- Requires additional memory for intermediate output.
- Usually needs a stable sorting algorithm for each digit pass.
- Performance depends on the number of digits.
- Handling negative numbers requires additional logic.
- It is not directly suitable for arbitrary values without a suitable digit representation.
18. Can Radix Sort Handle Negative Numbers?
The standard implementation in this lesson supports non-negative integers.
Negative integers require additional handling. One common approach is to separate negative and non-negative values.
- Separate negative numbers from non-negative numbers.
- Convert negative values to their absolute magnitudes carefully.
- Sort the magnitudes using Radix Sort.
- Reverse the sorted negative magnitudes and restore their negative signs.
- Sort the non-negative values normally.
- Combine the negative and non-negative parts.
19. Radix Sort vs Counting Sort
| Feature | Radix Sort | Counting Sort |
|---|---|---|
| Technique | Digit-by-digit sorting | Frequency counting |
| Comparison-based | No | No |
| Time Complexity | O(d × (n + b)) | O(n + k) |
| Space Complexity | O(n + b) | O(n + k) for stable version |
| Stable | Yes, with stable digit sorting | Yes, with cumulative-count implementation |
| Typical Input | Numbers or keys with digit representations | Integers in a manageable range |
20. Applications of Radix Sort
- Sorting large collections of integers.
- Sorting fixed-length identification numbers.
- Sorting postal codes and numeric codes.
- Sorting data with fixed-width integer keys.
- Sorting records by multiple digit-based fields.
- High-performance data-processing systems where keys have a suitable digit representation.
21. Common Mistakes in Radix Sort
- Using an unstable sorting method: Each digit pass must preserve the order of equal digit values.
- Starting from the wrong digit: LSD Radix Sort starts with the units digit.
- Incorrect digit extraction: Use (number / exp) % 10.
- Stopping too early: Continue until all digit positions of the maximum value have been processed.
- Incorrect cumulative counts: Stable placement needs cumulative frequencies.
- Traversing the input in the wrong direction: The standard stable Counting Sort placement pass traverses from right to left.
- Ignoring negative values: The standard implementation shown here is designed for non-negative integers.
- Integer overflow in digit position: Use a sufficiently wide type for the exponent when processing large integers.
22. Interview Questions
- What is Radix Sort?
- Is Radix Sort comparison-based?
- What are LSD and MSD Radix Sort?
- How does LSD Radix Sort work?
- Why is Counting Sort commonly used in Radix Sort?
- Why must the digit-sorting algorithm be stable?
- How do you extract a particular digit from a number?
- What is the time complexity of Radix Sort?
- What do n, d, and b represent in its complexity?
- What is the auxiliary space complexity of Radix Sort?
- Can Radix Sort handle negative numbers?
- What is the difference between Radix Sort and Counting Sort?
- When is Radix Sort more suitable than Quick Sort?
- What happens if an unstable sorting algorithm is used for each digit?
- What are the practical applications of Radix Sort?
23. Practice Problems
Problem 1: Sort an Array Using Radix Sort
Given an array of non-negative integers, sort it using LSD Radix Sort.
Input:
{170, 45, 75, 90, 802, 24, 2, 66}
Output:
{2, 24, 45, 66, 75, 90, 170, 802}
Problem 2: Sort Numbers with Different Digit Lengths
Sort the following numbers using Radix Sort. Remember that missing leading digits are treated as zero.
Input:
{5, 45, 1, 100, 9, 12}
Output:
{1, 5, 9, 12, 45, 100}
Problem 3: Implement Digit-Based Counting Sort
Write a stable Counting Sort function that sorts integers according to a specified digit position.
Input:
arr = {170, 45, 75, 90}
exp = 1
Task:
Sort according to the units digit.
Problem 4: Sort an Array with Negative Numbers
Extend Radix Sort to support both negative and non-negative integers.
Input:
{-45, 12, -3, 0, 8, -100}
Output:
{-100, -45, -3, 0, 8, 12}
Problem 5: Compare Radix Sort and Counting Sort
Given an integer array, determine whether Counting Sort or Radix Sort is more suitable based on the number of elements and the range or digit count.
Input:
n = 100000
Maximum value = 999999
Task:
Explain which algorithm may be more suitable and why.
24. Summary
- Radix Sort is a non-comparison-based sorting algorithm.
- It sorts numbers digit by digit.
- LSD Radix Sort starts with the units digit.
- MSD Radix Sort starts with the most significant digit.
- Counting Sort is commonly used for each digit pass.
- Each digit pass must use a stable sorting algorithm.
- Time complexity is O(d × (n + b)).
- Auxiliary space complexity is O(n + b).
- Negative numbers require additional handling.