~/coding-interview/radix-sort-algorithm-java.md

Radix Sort Algorithm

3 min readJuly 18, 2019by Gorav Singal#coding-interview#sorting-algorithms#radix-sort
// TL;DR

Sort numbers digit-by-digit starting from the least significant digit, using counting sort as a stable sub-routine. O(d × (n + k)) where d is digit count.

Radix Sort Algorithm

A number consists of digits. Example: 843. Its a 3-digit number. Radix sort, start by sorting numbers first by their most significant digit, then next, and so on.

So, in simpler terms. If there are maximum n numbers, and max d-digits in a number. This algorithm runs on array d times, and sort the numbers according to their current place digit.

To sort the numbers based on a digit, the any sorting technique can be used. But, most importantly the sort must be a stable sort.

Radix Sort Example

Radix Sort Algorithm

If you look at the pseudo code (assuming we have n numbers, and all are d-digits long):

for (int i=0; i<d; i++;) {
    //Sort the array on digit place-i
}

See the code here (explanation is below code):

public class RadixSort {
    private int[] arr;

    public RadixSort(int[] arr) {
        this.arr = arr;
    }

    /**
     * Using CountSort as stable sort
     */
    private void countSort(int position) {
        int[] c = new int[10];  //0 to 9
        for (int i=0; i<this.arr.length; i++) {
            int digit = this.getDigit(this.arr[i], position);
            c[digit] ++;
        }
        //accumulate
        for (int i=1; i<c.length; i++) {
            c[i] = c[i] + c[i-1];
        }

        int[] res = new int[this.arr.length];
        for (int i=this.arr.length-1; i>=0; i--) {
            int digit = this.getDigit(this.arr[i], position);

            res[c[digit]-1] = this.arr[i];
            c[digit] --;
        }

        this.arr = res;
        System.out.println(ArrayUtils.toString(arr));
    }

    private int getDigit(int num, int position) {
        return num/position % 10;
    }

    /**
     * Main method for radix sort
     */
    public void sort() {
        int max = ArrayUtils.getMaxValue(this.arr);
        
        int position = 1;

        while (max/position > 0) {
            this.countSort(position);

            position *= 10;
        }
    }
}

Explanation

  • First, we need to get the maximum number from the array. Since, Radix algorithm will run as long as the maximum number of digits in array.
  • In method countSort(), we are using count sort as helper sort algorithm. But, the catch here is that we need to sort the array based on the digit position. We are passing the position of digit.
  • We need a way to fetch the digit from the number. Note, we are passing the position
Example number: 839
Objective: We need 9, then 3, then 8

To get remainder, we need modulus (%) of a number by 10. We will get the last digit. But, how to get the any other digit?
See method: getDigit()

We first need to reduce the number by dividing with position. And, then take modulus with 10.

i.e. num/position % 10;
  • Lets get back to countSort()
  • As you have seen Count Sort
    • First, where we prepare array-c, to get the number of occurrences of a number. We modified that logic by taking that digit defined by position passed.
    • Then, we place number according the position.
  • And, we repeat this algorithm untill number of digits of maximum numbers finished.

Key Points

  • It is not a comparison sort.
  • It uses a stable sort as a helper sort method.
  • This sort the number according to the position of digits.
  • It is used for relatively smaller set of numbers.

Runtime complexity

The algorithm runs on time complexity of O(d(n + k)) ~= O(n) in worst/average case. Note: Count sort took O(n + k) time, this takes d times the count sort time.

Why Stable Sort is required as secondary sort here

Since, the radix algorithm works on digit-by-digit basis. Consider two numbers:

18
14

So, during first round, the order will become:

14
18

In second round, where we will be comparing most significant digit. If our algorithm is not stable, then any unstable algorithm might put the order like:

18
14

Which is wrong, Right!

$ subscribe --weekly

One deep dive a week, in your inbox

System design, AI engineering, trading systems and interview prep. Tested code, real numbers. Free, and you can unsubscribe any time.

or read it on gyanbyte.substack.com

Share

Related Posts

Counting Sort Algorithm

Counting Sort Algorithm

Counting sort runs on relatively smaller set of input. Counting sort calculates…

Heap Sort Algorithm

Heap Sort Algorithm

This is another very useful sorting algorithm based on Heap data structure. Read…

Quick Sort Algorithm

Quick Sort Algorithm

This algorithm is very useful for large input. And, is quite efficient one. It…

Merge Sort Algorithm

Merge Sort Algorithm

This algorithm is very efficient one, and is classic example of Divide and…

Bubble Sort Algorithm

Bubble Sort Algorithm

This is kind of preliminary technique of sorting. And, this is the first…

Selection Sort Algorithm

Selection Sort Algorithm

It is one of a simple algorithm to study for a beginner to understanding sorting…

Latest Posts

How to Stay Valuable as a Software Engineer in the AI Era: A Practical Playbook

How to Stay Valuable as a Software Engineer in the AI Era: A Practical Playbook

In the previous article I argued that AI is not killing software engineering…

How to Review AI-Generated Code: A Checklist for Catching What the Model Missed

How to Review AI-Generated Code: A Checklist for Catching What the Model Missed

A few months back I approved a PR that was almost entirely AI-generated. It…

How to Debug AI-Generated Code: Understand First, Fix Last

How to Debug AI-Generated Code: Understand First, Fix Last

In the last article I wrote about reviewing AI code before it goes in. This one…

The Future of Software Engineering: What AI Changes, What Stays, and Where the Jobs Go

The Future of Software Engineering: What AI Changes, What Stays, and Where the Jobs Go

Every few weeks somebody sends me a scary headline — “AI will replace all…

The Transactional Outbox Pattern: Never Lose an Event Again

The Transactional Outbox Pattern: Never Lose an Event Again

This is one of those patterns that looks like nothing until you get burnt once…

Event Sourcing, Explained: Store What Happened, Not Just the Final State

Event Sourcing, Explained: Store What Happened, Not Just the Final State

Here is a question I like to ask in interviews: your bank account shows a…