Skip to content
IT glossary
AlgorithmsUpdated December 3, 2026

Counting sort

Сортировка подсчётом

This sorting algorithm counts how often each integer key occurs and uses those counts to put the items in order. It works best when the keys span a small range.

The idea

Suppose you want to put a list of exam scores between 0 and 100 in order. Instead of comparing scores in pairs, make an array of 101 counters. Count how many students got each score, then write out each score as many times as it occurred, starting at 0. The order comes from the indices of the counter array, not from comparisons between input items.

Sorting plain integers

You don't need a counter for every integer from zero to the largest value. Use one for each integer between the minimum lo and maximum hi, inclusive. The index for a value x is x - lo, so the same approach works when the input includes negative numbers.

def counting_sort(values):
    if not values:
        return []
    lo, hi = min(values), max(values)
    counts = [0] * (hi - lo + 1)
    for x in values:
        counts[x - lo] += 1

    result = []
    for i, count in enumerate(counts):
        for _ in range(count):
            result.append(lo + i)
    return result

For [3, 1, 3, 0], the counts are [1, 1, 0, 2]. The zero count contributes nothing, so the result is [0, 1, 3, 3].

Sorting records without changing the order of ties

If you're sorting tickets by numeric priority, writing out the priority values loses the tickets themselves. Instead, take the prefix sums of the counts. Each cumulative count tells you how many records have that key or a smaller one, so it marks the exclusive end of that key's block in the output array. Scan the input from right to left. For each record, decrement its key's cumulative count and use the new value as its output index. The later of two tied records takes the rightmost available slot, leaving the earlier record to its left. This makes the sort stable.

Choosing it in practice and in interviews

For n items and a key range of width k = hi - lo + 1, counting sort takes O(n + k) time. The counters take O(k) space. The code above also allocates an O(n) result list, as does the usual stable version. When sorting plain integers, you can instead write the values back into the input and use only O(k) extra space.

Look for a small, known range, such as byte values, or a stable pass over a single digit in radix sort. Don't confuse the width of the range with the number of distinct keys: [0, 1_000_000_000] has only two distinct values, but the counter array would need more than a billion entries. In an interview, state both n and k before calling the algorithm linear. If asked about the Ω(n log n) lower bound, explain that it applies to comparison-based sorting, whereas counting sort uses integer keys to index an array directly.