Python 3D Academyবাংলা

Counting sort: beating n log n when the keys are small

🌍 In real life. The school office must list its 2,000 students by age for the sports day groups. Every student is 10 to 17 years old. Comparing students two at a time would take tens of thousands of comparisons. The office does something smarter: it puts out 8 boxes labelled 10, 11, …, 17, walks through the register once and drops each student's card into the box for their age, then picks the boxes up in order, 10 first. Two walks, and no student is ever compared with another.

This is counting sort. It works because the keys (ages) come from a small range that you know in advance.

The idea in one sentence: when every key is a small whole number from 0 to k − 1, count how many times each key appears, then write the keys out in order as many times as they were counted.

Its words:

  • key range k: how many different keys are possible (8 ages; 101 marks from 0 to 100)
  • count array: counts[x] is how many times key x appears
  • comparison sort: a sort that only learns about the order by comparing two values; every sort so far
  • non-comparison sort: a sort that uses the keys as positions instead, like counting sort

Step by step:

  1. make counts = [0] * k
  2. walk the list once: for each value x, counts[x] += 1
  3. walk the keys 0 to k − 1: write each key counts[x] times

The bars drop into the counts below, then the counts are written out as the sorted row:

Why it is correct. Every copy of a key is counted once, so the output has exactly the same values as the input. The keys are written in increasing order 0, 1, 2, …, so every copy of x comes after every smaller key: the output is sorted.

Sorting records by a small key, stably. To sort students (not just ages), keep a box (a list) per key instead of a number: append each student to the box for their age, then join the boxes in order. Students of the same age come out in the order they went in, so this version is stable.

What it costs, by counting. One walk over the n values to count, and one walk over the k keys to write: O(n + k) steps, and O(k) memory for the counts (plus the output). For 2,000 students and 8 ages that is about 2,000 steps. A comparison sort needs about n log₂ n ≈ 22,000 comparisons, and no comparison sort can do better than about n log₂ n in the worst case: there are n! possible orders, each comparison has only two answers, so telling them all apart takes at least log₂(n!) ≈ n log₂ n comparisons. Counting sort escapes this limit because it never compares. The catch: k must be small. Sorting phone numbers this way would need a count for every possible number, billions of them.

def counting_sort(a, k):
    counts = [0] * k                   # counts[x]: how many times x appears
    for x in a:
        counts[x] += 1
    out = []
    for x in range(k):                 # smallest key first
        out += [x] * counts[x]
    return out

print(counting_sort([3, 1, 4, 1, 2, 3, 1], 5))

def sort_by_age(students, low=10, high=17):
    boxes = [[] for _ in range(high - low + 1)]   # one box per age
    for name, age in students:
        boxes[age - low].append(name)             # same age: keeps the order
    return [name for box in boxes for name in box]

students = [("Rina", 12), ("Ali", 10), ("Sumi", 12), ("Joy", 11), ("Tia", 10)]
print(sort_by_age(students))

Mistakes and edge cases.

  • k too small: a value equal to k or bigger is past the end of counts: IndexError: list index out of range; k is the number of possible keys, so the biggest key is k − 1
  • negative values or a range that doesn't start at 0: subtract the smallest possible key first, as age - low does
  • a huge key range: with values up to a million, counts needs a million slots even for 10 values; use a comparison sort
  • writing [x] * counts[x] for records: it would make copies of the key, not of the students; keep boxes of records instead
  • only whole-number keys: counting sort can't sort floats or names directly

Quiz

  1. What does this print?

    a = [2, 0, 2, 1, 0, 2]
    counts = [0] * 3
    for x in a:
        counts[x] += 1
    print(counts)
    print([x for x in range(3) for _ in range(counts[x])])
  2. n values with keys from 0 to k − 1. What does counting sort cost?

    • O(n + k)
    • O(n log n)
    • O(n × k)
  3. How can counting sort beat the n log n limit of comparison sorts?

    • It never compares two values: it uses each key as a position
    • It compares faster
    • The limit is wrong
  4. Which job is a bad fit for counting sort?

    • Sorting 100 bank balances that go up to 10 crore taka
    • Sorting 10,000 exam marks from 0 to 100
    • Sorting 5,000 students by class, 1 to 10
  5. Ages run from 10 to 17, and this raises IndexError. Which line is wrong?

    def sort_ages(ages):
        counts = [0] * 8
        for age in ages:
            counts[age] += 1
        out = []
        for i in range(8):
            out += [i + 10] * counts[i]
        return out

Coding tasks

  1. Write counting_sort(a, k): every value of a is a whole number from 0 to k − 1. Return a new sorted list by counting, without comparing values (no sort, sorted, min, max or <).

  2. Write sort_by_age(students, low=10, high=17): students is a list of (name, age) pairs with ages from low to high. Return the names sorted by age, youngest first, using one box per age; students of the same age keep their order in the list.