Algo-Sim › Sorting & Divide and Conquer

Counting Sort

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

When values come from a small range, count how many of each there are and write them back in order. O(n + k) and no comparisons at all.

Problem

Sort nums, whose values all fall in a small range 0..k − 1, without comparing elements: count how many times each value occurs, then write the values back in order.

Constraints

Edge cases to test

Follow-up questions

How do you make it stable?
Turn the counts into prefix sums and place items from the back: needed when sorting records by a key, as radix sort does.
When is it the right tool?
When the range k is O(n): sorting in O(n + k), e.g. ages, grades or bytes.

Solution

Java

public int[] countingSort(int[] nums) {
    int[] count = new int[10];
    for (int x : nums) count[x]++;
    int i = 0;
    for (int v = 0; v < 10; v++) {
        for (int c = 0; c < count[v]; c++) {
            nums[i++] = v;
        }
    }
    return nums;
}

Python

def counting_sort(nums):
    count = [0] * 10
    for x in nums:
        count[x] += 1
    i = 0
    for v in range(10):
        for _ in range(count[v]):
            nums[i] = v
            i += 1
    return nums

C++

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

class Solution {
  public:
    vector<int> countingSort(vector<int> &nums) {
        vector<int> count = vector<int>(10);
        for (int x : nums)
            count[x]++;
        int i = 0;
        for (int v = 0; v < 10; v++) {
            for (int c = 0; c < count[v]; c++) {
                nums[i++] = v;
            }
        }
        return nums;
    }
};

More Sorting & Divide and Conquer problems