Radix Sort is a linear sorting algorithm (for fixed length digit counts) that sorts elements by processing them digit by digit. It is an efficient sorting algorithm for integers or strings with fixed-size keys.
It repeatedly distributes the elements into buckets based on each digit's value. This is different from other algorithms like Merge Sort or Quick Sort where we compare elements directly.
By repeatedly sorting the elements by their significant digits, from the least significant to the most significant, it achieves the final sorted order.
We use a stable algorithm like Counting Sort to sort the individual digits so that the overall algorithm remains stable.
To perform radix sort on the array [170, 45, 75, 90, 802, 24, 2, 66], we follow these steps:
Step 1: Find the largest element, which is 802. It has three digits, so we will iterate three times.
Step 2: Sort the elements based on the unit place digits (X=0).
👁 Image How does Radix Sort Algorithm work | Step 2
Step 3: Sort the elements based on the tens place digits.
👁 Image How does Radix Sort Algorithm work | Step 3
Step 4: Sort the elements based on the hundreds place digits.
👁 Image How does Radix Sort Algorithm work | Step 4
Step 5: The array is now sorted in ascending order.
👁 Image How does Radix Sort Algorithm work | Step 5
Below is the implementation for the above illustrations:
Output
2 24 45 66 75 90 170 802
Complexity Analysis of Radix Sort:
Time Complexity:
Radix sort is a non-comparative integer sorting algorithm that sorts data with integer keys by grouping the keys by the individual digits which share the same significant position and value. It has a time complexity of O(d * (n + b)), where d is the number of digits, n is the number of elements, and b is the base of the number system being used.
In practical implementations, radix sort is often faster than other comparison-based sorting algorithms, such as quicksort or merge sort, for large datasets, especially when the keys have many digits. However, its time complexity grows linearly with the number of digits, and so it is not as efficient for small datasets.
Auxiliary Space:
Radix sort also has a space complexity of O(n + b), where n is the number of elements and b is the base of the number system. This space complexity comes from the need to create buckets for each digit value and to copy the elements back to the original array after each digit has been sorted.