Skip to content

Counting Sort ​

Counting sort counts how many times each number appears, then uses those counts to directly calculate where each value should go.

At a Glance ​

  • Counting = counting how many there are. It needs a step that counts how many times each number appears.
  • As an analogy, to sort students in a class by height without comparing them to each other, you draw boxes on the floor for 140cm, 141cm, and so on, have each student stand in the box for their height, then call them out starting from the first box.
  • It is a non-comparison sort, which does not compare elements with each other.
  • If you use running totals and fill from the back, as in the code below, it is a stable sort.
  • It needs a separate count array and result array, so it is not an in-place sort.

The Limit of Comparison Sorts ​

There are N! ways to order N elements. A comparison sort repeatedly asks yes/no questions like "is a < b?", so if you draw the questioning process as a tree (a decision tree) of height h, it has at most 2^h endpoints (leaf nodes).

  • To tell every case apart, there must be at least N! leaf nodes, so 2^h ≥ N! must hold.
  • Taking the log of both sides gives h ≥ log₂(N!), and log₂(N!) grows at the same rate as n log n (Θ(n log n)).
  • h is the number of comparisons in the worst case, which is the time complexity of a comparison sort. So no comparison sort can be faster than Ω(n log n) in the worst case.

The way to get below this O(n log n) is to not compare at all. Counting sort sorts by "counting" instead of comparing.

How It Works ​

  1. Size the counting array so it can hold the maximum value (if the maximum is 5, then 0 ~ 5, 6 slots).
  2. Walk the array once and increase the slot for each value by 1.
  3. Turn the counting array into running totals. Now counting[v] is "the number of values that are v or less," which is the last position for v, plus 1.
  4. Walk the original array from the back, decrease that value's slot by 1, and put the value at that position.

Example array [2, 5, 3, 0, 2, 3, 0, 3] (maximum 5):

Value012345
Step 2: occurrences202301
Step 3: running total224778

Here is step 4, filling from the back.

OrderValue taken (original position)Position filledResult array
13 (index 7)6[-, -, -, -, -, -, 3, -]
20 (index 6)1[-, 0, -, -, -, -, 3, -]
33 (index 5)5[-, 0, -, -, -, 3, 3, -]
42 (index 4)3[-, 0, -, 2, -, 3, 3, -]
50 (index 3)0[0, 0, -, 2, -, 3, 3, -]
63 (index 2)4[0, 0, -, 2, 3, 3, 3, -]
75 (index 1)7[0, 0, -, 2, 3, 3, 3, 5]
82 (index 0)2[0, 0, 2, 2, 3, 3, 3, 5]

The 3 that was further back goes into a later position (index 6), so equal values keep their original order.

Python Code ​

python
def counting_sort(arr):
    if not arr:
        return []
    # 1. Create a counting array that can hold values up to the maximum
    counting = [0] * (max(arr) + 1)
    sorted_arr = [0] * len(arr)

    # 2. Count how many times each number appears
    for x in arr:
        counting[x] += 1

    # 3. Convert to running totals → "how many values are this number or less"
    for i in range(1, len(counting)):
        counting[i] += counting[i - 1]

    # 4. Walk from the back and put each value in its place (going from the back makes it stable)
    for i in range(len(arr) - 1, -1, -1):
        counting[arr[i]] -= 1
        sorted_arr[counting[arr[i]]] = arr[i]

    return sorted_arr


print(counting_sort([5, 4, 3, 2, 1]))
# Output: [1, 2, 3, 4, 5]
print(counting_sort([3, 1, 4, 1, 5, 9, 2, 6]))
# Output: [1, 1, 2, 3, 4, 5, 6, 9]
  1. If the maximum is 5, it creates 6 slots to hold 0 ~ 5. This is counting sort's weakness. The counting array has to be as large as the range of possible values, so it becomes inefficient when that range is wide.
  2. It walks the array once and increments the slot for each value by 1.
  3. It keeps adding the previous slot's value to build running totals.
  4. Walking from the back, it first decrements the slot number by 1, then puts the value at that position. When there are several equal values, the one further back goes into a later position, which makes it a stable sort.

When Negative Numbers Are Mixed In ​

The code above uses values directly as slot numbers, so it can only sort integers 0 or greater. If there are negative numbers, shift the minimum value to slot 0 and count from there.

python
def counting_sort_with_negative(arr):
    if not arr:
        return []
    # 1. Shift the minimum to slot 0 and count (number of slots = max - min + 1)
    lo = min(arr)
    counting = [0] * (max(arr) - lo + 1)
    sorted_arr = [0] * len(arr)

    for x in arr:
        counting[x - lo] += 1
    for i in range(1, len(counting)):
        counting[i] += counting[i - 1]
    # 2. The rest is the same as the code above; only the slot number changes to x - lo
    for i in range(len(arr) - 1, -1, -1):
        counting[arr[i] - lo] -= 1
        sorted_arr[counting[arr[i] - lo]] = arr[i]
    return sorted_arr


print(counting_sort_with_negative([3, -2, 0, -5, 3, 1]))
# Output: [-5, -2, 0, 1, 3, 3]
  1. Value x is counted in slot x - lo. If the minimum is -5, then -5 goes in slot 0 and 3 goes in slot 8. This way, even when the minimum is large (e.g. 1000 ~ 1010), only 11 slots are needed.
  2. The running totals and filling from the back stay the same; the only difference is computing the slot number as x - lo.

Time and Space Complexity ​

CaseTime complexity
BestO(n + k)
AverageO(n + k)
WorstO(n + k)
  • n is the number of elements, and k is the range of values (the maximum value in the array, if starting from 0). It is O(n) for scanning the array a few times plus O(k) for scanning the counting array.
  • If k is no larger than n, it is a very fast O(n), but if a single value is very large (e.g. 3 elements but a maximum of 100 million), k actually makes it slower.
  • Space complexity: O(n + k) extra memory. The counting array O(k) plus the result array O(n).

Pros and Cons ​

  • Use: Use it when the numbers being sorted fall within a specific narrow range. (e.g. scores 0 ~ 100, ages, letters of the alphabet) When building a Suffix Array, using counting sort (radix sort) also lets you get it in O(n log n). With a comparison sort it is O(n log² n).

Pros ​

  • If the value range k is small, around n, it can sort in O(n).
  • It is a stable sort, so it is used as the per-digit sorting step of radix sort.

Cons ​

  • Regardless of the array size n, the counting array grows as large as the value range k. If the range is wide, a lot of memory is wasted.
  • It can only sort values that can be turned into slot numbers, such as integers.

Summary ​

ConceptPlain-language summary
Counting sortMake a slot for each value, count them, then take them out in slot order
Running totalFind your position directly with "how many are less than or equal to me"
Filling from the backThe trick that keeps equal values in their original order (stable sort)
WeaknessIf the value range is wide, there are too many slots and memory is wasted