Counting Sort in C#: Linear-Time Sorting for Small Integer Ranges

Counting sort does not compare elements at all. It counts how many times each value occurs, then uses those counts to work out where each value belongs in the output. When the values are integers in a small range, such as ages, exam scores, or bytes, this runs in linear time and beats every comparison-based sort.

The catch is in “small range”. The algorithm allocates one counter per possible value between the minimum and the maximum, so sorting ten numbers between 1 and 1,000,000,000 would allocate four gigabytes of counters.

Usage

int[] numbers = { 1, 5, 4, 11, 20, 8, 2, 98, 90, 16 };

int[] sorted = CountingSort.Sort(numbers);

Console.WriteLine(string.Join(", ", sorted));
// 1, 2, 4, 5, 8, 11, 16, 20, 90, 98

The method returns a new array and leaves the input unchanged. Negative numbers work too, because counters are indexed relative to the smallest value.

Implementation

public static class CountingSort
{
    public static int[] Sort(ReadOnlySpan<int> items)
    {
        if (items.IsEmpty) return [];

        // 1. Find the range of values.
        int min = items[0], max = items[0];
        foreach (int value in items)
        {
            if (value < min) min = value;
            else if (value > max) max = value;
        }

        long range = (long)max - min + 1;
        if (range > Array.MaxLength)
            throw new ArgumentException("The range of values is too large for counting sort.", nameof(items));

        // 2. Count how often each value occurs.
        int[] counts = new int[range];
        foreach (int value in items)
            counts[value - min]++;

        // 3. Turn counts into end positions: counts[v] = number of elements <= v.
        for (int i = 1; i < counts.Length; i++)
            counts[i] += counts[i - 1];

        // 4. Place elements, walking backwards to keep the sort stable.
        int[] result = new int[items.Length];
        for (int i = items.Length - 1; i >= 0; i--)
        {
            int slot = --counts[items[i] - min];
            result[slot] = items[i];
        }

        return result;
    }
}

int[] converts implicitly to ReadOnlySpan<int>, so you can pass an array, a slice such as numbers.AsSpan(2, 5), or a stack-allocated buffer. Array.MaxLength requires .NET 6 or later.

How it works

Range. One pass finds the smallest and largest values. The range is calculated as a long because max - min overflows an int when the input contains both large positive and large negative numbers. The check against Array.MaxLength also guarantees that value - min fits in an int later.

Counting. counts[v - min] holds how many times v appears. Subtracting min is what lets negative numbers and ranges like 1000 to 1100 work without wasting memory on the values below.

Prefix sums. After step 3, each counter holds the number of elements less than or equal to its value, which is exactly one past the last position that value will occupy in the output.

Placement. Walking the input from the end and decrementing the counter before each write puts equal values into their slots from right to left, so the last one seen goes last. The result is stable: equal values keep their original order. For plain integers stability is invisible, but it matters when you sort records by an integer key, and it is the reason counting sort can serve as the inner step of radix sort.

If you only sort plain integers and do not care about stability, steps 3 and 4 can be replaced by a simpler loop that writes each value counts[v] times. The prefix-sum version above is the one that generalizes.

Complexity

CaseTimeExtra space
All casesO(n + k)O(n + k)

Here n is the number of elements and k the size of the range (max - min + 1). When k is about the same size as n or smaller, the sort is linear. When k is much larger than n, the counting array dominates both time and memory.

When to use counting sort

Use it for integer keys with a known, narrow range: grades from 0 to 100, ages, priorities, enum values, bytes. It is also the building block of radix sort, which sorts larger integers digit by digit with a counting sort per digit.

Do not use it for floating-point values, strings or data with a wide or unknown range. For those, Array.Sort is the right default, and quick sort or merge sort are the comparison-based algorithms worth knowing.

Related sorting examples

1 thought on “Counting Sort in C#: Linear-Time Sorting for Small Integer Ranges”

Leave a Comment