In this tutorial, you will learn how radix sort works. Also, you will find working examples of radix sort in C, C++, Java and Python. Radix sort is a sorting technique that sorts the elements by first grouping the individual digits of the same place value. Then, sort the elements according to their increasing/decreasing order.

Suppose, we have an array of 8 elements. First, we will sort elements based on the value of the unit place. Then, we will sort elements based on the value of the tenth place. This process goes on until the last significant place. Let the initial array by [121, 432, 564, 23, 1, 45, 788]. 

How does Radix Sort Work?

  1. Find the largest element in the array, i.e. max. Let X be the number of digits in max. X is calculated because we have to go through all the significant places of all elements. In this array[121, 432, 564, 23, 1, 45, 788], we have the largest number 788. It has 3 digits. Therefore, the loop should go up to hundreds of places (3 times).
  2. Now, go through each significant place one by one. Use any stable sorting technique to sort the digits at each significant place. We have used counting sorting for this. Sort the elements based on the unit place digits (X=0).
  3. Now, sort the elements based on digits at the tens place.
  4. Finally, the elements are sorted based on the digits in hundreds of places.

Radix Sort Algorithm

Python, Java and C/C++ Examples

Complexity

Since radix sort is a non-comparative algorithm, it has advantages over comparative sorting algorithms. For the radix sort that uses counting sort as an intermediate stable sort, the time complexity is O(d(n+k)). Here, d is the number cycle and O(n+k) is the time complexity of counting sort. Thus, radix sort has linear time complexity which is better than O(nlog n) of comparative sorting algorithms.

If we take very large digit numbers or the number of other bases like 32-bit and 64-bit numbers then it can perform in linear time however the intermediate sort takes large space. This makes radix sort space inefficient. This is the reason why this sort is not used in software libraries.

Radix Sort Applications

Radix sort is implemented in

  • DC3 algorithm (Kärkkäinen-Sanders-Burkhardt) while making a suffix array.
  • places where there are numbers in large ranges.

Leave a Comment