Algo-Sim › Sorting & Divide and Conquer

Radix Sort (LSD)

Medium · Sorting & Divide and Conquer · step through it in Java, Python and C++ on your own input

Sort non-negative integers digit by digit, least significant first, with a stable counting sort per digit: O(d · (n + 10)) and no comparisons.

Problem

Sort an array of non-negative integers without comparing them. Run one stable counting sort per decimal digit, starting from the ones digit and ending with the most significant digit of the largest value.

Constraints

Edge cases to test

Follow-up questions

Why must each pass be stable?
Pass k only looks at digit k. Stability keeps numbers with the same digit k in the order the earlier passes put them, which is their order by the lower digits.
What about negative numbers?
Shift every value by the minimum first, or sort the negatives and the non-negatives separately and reverse the negatives. Still O(d · (n + b)).
When does it beat O(n log n)?
When d is small next to log n, e.g. 32-bit keys in base 256: 4 passes of O(n + 256). It is also how Maximum Gap (LC 164) gets O(n).

Solution

Java

public int[] radixSort(int[] nums) {
    int max = 0;
    for (int x : nums) max = Math.max(max, x);
    int[] out = new int[nums.length];
    for (int exp = 1; max / exp > 0; exp *= 10) {
        int[] count = new int[10];
        for (int x : nums) count[(x / exp) % 10]++;
        for (int d = 1; d < 10; d++) count[d] += count[d - 1];
        for (int i = nums.length - 1; i >= 0; i--) {
            int d = (nums[i] / exp) % 10;
            out[--count[d]] = nums[i];
        }
        System.arraycopy(out, 0, nums, 0, nums.length);
    }
    return nums;
}

Python

def radix_sort(nums):
    big = max(nums)
    out = [0] * len(nums)
    exp = 1
    while big // exp > 0:
        count = [0] * 10
        for x in nums:
            count[x // exp % 10] += 1
        for d in range(1, 10):
            count[d] += count[d - 1]
        for i in range(len(nums) - 1, -1, -1):
            d = nums[i] // exp % 10
            count[d] -= 1
            out[count[d]] = nums[i]
        nums[:] = out
        exp *= 10
    return nums

C++

#include <bits/stdc++.h>
using namespace std;

class Solution {
  public:
    vector<int> radixSort(vector<int> &nums) {
        int max = 0;
        for (int x : nums)
            max = std::max(max, x);
        vector<int> out = vector<int>(nums.size());
        for (long long exp = 1; max / exp > 0; exp *= 10) {
            vector<int> count = vector<int>(10);
            for (int x : nums)
                count[(x / exp) % 10]++;
            for (int d = 1; d < 10; d++)
                count[d] += count[d - 1];
            for (int i = int(nums.size()) - 1; i >= 0; i--) {
                int d = (nums[i] / exp) % 10;
                out[--count[d]] = nums[i];
            }
            nums = out;
        }
        return nums;
    }
};

More Sorting & Divide and Conquer problems