Skip to content

Counting sort

ordering

Level 2 of 3

how it works

The idea in a few sentences and a picture, then one row sorted step by step.

Counting sort never compares two numbers. It works on whole numbers from 0 to 9. First it counts how many numbers there are of each value: the tallies. Then it adds the total before each tally to it, so each total says how many numbers are that value or smaller. On 4, 1, 3, 1, 0, 3, 2, 4 the tallies for 0 to 4 are 1, 2, 1, 2, 2, and the totals 1, 3, 4, 6, 8. Three numbers are 1 or smaller, so in order they fill places 1 to 3, and the last 1 goes in place 3. Last, from the last number back to the first, it sends each number into a second row, at the place its total says, and takes one off that total. Of the two 1s, the later is sent first, to place 3, and the earlier to place 2: equal numbers keep their order, so the sort is stable.

counted: how many of each value1412113314125063272842valuetally01122132425060708090added up: how many of that value or smallervaluetallytotal011123214326428508608708808908sent from the last number back1412113314125063272842123456784282432601123315112417
Counting sort on 4, 1, 3, 1, 0, 3, 2, 4. The tallies, then the totals, then each number sent from the back to its place. Equal numbers keep their order.
A short shuffle: 7 moments of its 27 steps, the steps between them left for the watch page
  1. step 2 of 27

    4131032401234567890000100000

    Count 4: its tally is now 1.

    what it remembers to know where it is
    number
    4
    tally
    1

    watch from here

  2. step 9 of 27

    4131032401234567891212200000

    Count 4: its tally is now 2.

    what it remembers to know where it is
    number
    4
    tally
    2

    watch from here

  3. step 18 of 27

    4131032401234567891346888888

    8 numbers are 9 or smaller.

    what it remembers to know where it is
    number
    9
    tally
    8

    watch from here

  4. step 19 of 27

    4131032401234567891346788888

    The total for 4 is 8, so 4 goes to place 8, and the total drops to 7.

    what it remembers to know where it is
    number
    4
    tally
    7

    watch from here

  5. step 23 of 27

    0412133401234567890235788888

    The total for 1 is 3, so 1 goes to place 3, and the total drops to 2.

    what it remembers to know where it is
    number
    1
    tally
    2

    watch from here

  6. step 25 of 27

    0112334401234567890134788888

    The total for 1 is 2, so 1 goes to place 2, and the total drops to 1.

    what it remembers to know where it is
    number
    1
    tally
    1

    watch from here

  7. step 27 of 27

    0112334401234567890134688888

    In order, without comparing two numbers: 8 numbers counted, 9 totals added and 8 numbers placed.

    what it remembers to know where it is
    number
    not yet
    tally
    not yet

    Where it says not yet, nothing is held there at that moment.

    watch from here

the steps, in plain words
  1. start a tally of 0 for every value from 0 to 9Python line 10
  2. count each number into the tally for its valuePython lines 11 and 12
  3. add each tally to the ones before it: now it says how many numbers are that value or smallerPython lines 14 and 15
  4. from the last number back to the first, send it to the place its total says, and take one offPython lines 17, 18, 19, 20 and 21
the same in Python

The steps in plain words are what to learn. Python is a programming language, and the code below does the same steps, for those who code. Python numbers the places in a list from 0, not 1: the first number is numbers[0], the second numbers[1], and so on.

def counting_sort(numbers):
    """Put a list of whole numbers from 0 to 9 in order, smallest first, in
    the list itself, without comparing two of them.

    Count how many numbers there are of each value. Add the total before
    each tally to it, so it says how many numbers are that value or smaller.
    Then, from the last number back to the first, send each number to the
    place its total says, and take one off that total.
    """
    tally = [0] * 10  # a tally of 0 for every value from 0 to 9
    for number in numbers:  # count each number into the tally for its value
        tally[number] += 1

    for value in range(1, 10):  # add the total before it to each tally
        tally[value] += tally[value - 1]

    row = numbers.copy()  # the numbers as they stood, read from the back
    for number in reversed(row):  # from the last number back to the first
        tally[number] -= 1  # take one off its total: its place, from 0
        numbers[tally[number]] = number  # send it there
    return numbers

how it scales

How the placings grow, from ten numbers to ten million.

Each step across or up is ten times the one before, a log-log plot. The line climbs one step up for each step across: ten times the numbers, ten times the placings. Every row of nn numbers places exactly nn, so the points sit on the line.

placed, ten times more at each mark up

slope 1102104106101102103104105106107slope 1101102103104105106107101102103104105106107slope 1101102103104105106107101102103104105106107

nn, how many numbers are in the row, ten times more at each mark to the right

  • every row, whatever its ordersolid where measured by running it; dashed where its formula carries it on to ten millionslope 1: ten times n, 10 times the work
what a shuffled row costs on average, at a billion placed a second
nnplacedtime
1,0001,000about 1 microsecond
100,000100,000about 100 microseconds
10,000,00010,000,000about 10 milliseconds

The placed are the same on any computer. The times are not: a real computer may be faster or slower than a billion a second.

make these counts yourself

Copy this script and run it with Python 3.12 or later. It counts the same steps as the plot. Where a count depends on a random shuffle, yours will differ a little.

"""Count counting sort's steps yourself, as the plot on this page does.

Run it with Python 3.12 or later. For each size n it prints how many numbers
are placed on a row in order, on a row back to front, and on a row of random
whole numbers from 0 to 9. Every row of n numbers gives the same count, n.
The counts are the same on any computer; only the time taken differs.
"""
import random


class Placed(list):
    """A list that counts every number sent to a place in it."""

    count = 0

    def __setitem__(self, place, number):
        Placed.count += 1
        super().__setitem__(place, number)


def counting_sort(numbers):
    """Put a list of whole numbers from 0 to 9 in order, smallest first, in
    the list itself, without comparing two of them.

    Count how many numbers there are of each value. Add the total before
    each tally to it, so it says how many numbers are that value or smaller.
    Then, from the last number back to the first, send each number to the
    place its total says, and take one off that total.
    """
    tally = [0] * 10  # a tally of 0 for every value from 0 to 9
    for number in numbers:  # count each number into the tally for its value
        tally[number] += 1

    for value in range(1, 10):  # add the total before it to each tally
        tally[value] += tally[value - 1]

    row = numbers.copy()  # the numbers as they stood, read from the back
    for number in reversed(row):  # from the last number back to the first
        tally[number] -= 1  # take one off its total: its place, from 0
        numbers[tally[number]] = number  # send it there
    return numbers


def in_order(n):
    """n whole numbers from 0 to 9 in order, spread as evenly as they go."""
    return [i * 10 // n for i in range(n)]


def count(row):
    """How many numbers counting sort places on this row."""
    Placed.count = 0
    counting_sort(Placed(row))
    return Placed.count


if __name__ == "__main__":
    random.seed(1)
    print(f"{'n':>9} {'in order':>10} {'back to front':>14} {'random':>10}")
    for n in [10, 100, 1000, 10_000, 100_000, 1_000_000]:
        shuffled = [random.randrange(10) for _ in range(n)]
        row = in_order(n)
        print(f"{n:>9} {count(row):>10} {count(row[::-1]):>14} {count(shuffled):>10}")

extra memory, the places the sort holds beyond the row itself, ten times more at each mark up

slope 1102104106108101102103104105106107slope 1101102103104105106107108101102103104105106107slope 1101102103104105106107108101102103104105106107

nn, how many numbers are in the row, ten times more at each mark to the right

  • every row, whatever its ordersolid where measured by running it; dashed where its formula carries it on to ten millionslope 1: ten times n, 10 times the room

best, worst and average

No row is cheaper or dearer than another. How many steps counting sort takes never depends on the values or their order, only on how many numbers there are. So the grid has one column. The picture counts three rows of 8 numbers: each takes 8 counts, 9 additions and 8 placings.

A case is one kind of input, the thing the method is given, such as a row back to front, whatever its length. A bound says how fast that case's cost grows as the input gets longer.

The counts are in the grid. A count is often the sum of pieces that grow at different speeds, and on long inputs the fastest-growing piece swamps the rest. For example, a count of half of n times n, less half of n: at 2,000 items, 2,000,000 less 1,000. So how a cost grows is what tells one method from another, and the bounds keep just that.

what each case costs, and how fast that cost grows; section 4 works out every formula in it
averageevery row, whatever its order
countednn
totals added99
placednn
how the placed grow in each case
tight, Θ\ThetaΘ(n)\Theta(n)
ceiling, OOO(n)O(n)
floor, Ω\OmegaΩ(n)\Omega(n)

extra memory: a second row of n places and 10 tallies

Extra memory is the room it needs on top of the input itself, while it runs.

rowcountedadditionsplaced
0, 1, 2, 3, 5, 6, 7, 8898
8, 7, 6, 5, 3, 2, 1, 0898
4, 1, 3, 1, 0, 3, 2, 4898
Three rows of 8 numbers, in order, back to front and mixed. Every count is the same.

where the formula comes from

Each count above, worked out in small steps, each naming the line it comes from.

Why does counting sort place exactly nn numbers, on every row?
  1. the move: see the last pass

    the line:
    the last pass sendseach number once\begin{gathered} \text{the last pass sends} \\ \text{each number once} \end{gathered}
    sent from the last number back121203224112341222401213
    The last pass on 2, 0, 2, 1. From the back, 1 goes to place 2, then 2 to place 4, 0 to place 1 and the first 2 to place 3. Four placings.

    why it is allowed: From the last number back to the first, each number is sent to its place and never moved again. The picture sends 2, 0, 2, 1.

  2. the move: one for each number

    the line:
    P=1+1+⋯+1P = 1 + 1 + \dots + 1

    why it is allowed: PP is the numbers placed. By line 1, one placing for each of the nn numbers.

  3. the move: add the ones

    the line:
    P=nP = n

    why it is allowed: By line 2, nn ones add up to nn. For 2, 0, 2, 1, that is 4.

  4. the move: any row

    the line:
    the same for everyrow of n numbers\begin{gathered} \text{the same for every} \\ \text{row of } n \text{ numbers} \end{gathered}

    why it is allowed: In line 1, how many sends there are never depends on a number's value or where it stands, only on its being there.

  5. the move: a ceiling

    the line:
    P≤nP \le n

    why it is allowed: By line 3, PP is nn, so it is at most nn.

  6. the move: read it as a bound

    the line:
    P∈O(n)P \in O(n)

    why it is allowed: By line 5, PP is at most 1 times nn.

  7. the move: a floor

    the line:
    P≥nP \ge n

    why it is allowed: By line 3, PP is at least nn too.

  8. the move: read it as a bound

    the line:
    P∈Ω(n)P \in \Omega(n)

    why it is allowed: By line 7, PP never drops below 1 times nn.

  9. the move: ceiling and floor together

    the line:
    P∈Θ(n)P \in \Theta(n)

    why it is allowed: Lines 6 and 8 bound PP by the same growth, nn.

try it on small rows: over every order of 4 numbers, the average is P=4P = 4

Why does counting sort count exactly nn numbers?
  1. the move: see the first pass

    the line:
    the first pass countseach number once\begin{gathered} \text{the first pass counts} \\ \text{each number once} \end{gathered}
    counted: how many of each value1212032241valuetally01112230405060708090
    The first pass on 2, 0, 2, 1. The tally for 0 ends at 1, for 1 at 1, and for 2 at 2. Four counts.

    why it is allowed: From the first number to the last, each adds 1 to the tally for its value. The picture counts 2, 0, 2, 1.

  2. the move: one for each number

    the line:
    C=1+1+⋯+1C = 1 + 1 + \dots + 1

    why it is allowed: CC is the numbers counted. By line 1, one count for each of the nn numbers.

  3. the move: add the ones

    the line:
    C=nC = n

    why it is allowed: By line 2, nn ones add up to nn. For 2, 0, 2, 1, that is 4.

try it on small rows: over every order of 4 numbers, the average is C=4C = 4

Why does counting sort add exactly 9 totals, whatever the row?
  1. the move: the first total

    the line:
    the total for 0is its own tally\begin{gathered} \text{the total for 0} \\ \text{is its own tally} \end{gathered}

    why it is allowed: No value is below 0, so nothing is added to it.

  2. the move: one addition for each value after it

    the line:
    each value from 1 to 9 addsthe total before it, once\begin{gathered} \text{each value from 1 to 9 adds} \\ \text{the total before it, once} \end{gathered}
    added up: how many of that value or smallervaluetallytotal011112224304404504604704804904
    The totals of 2, 0, 2, 1. The tallies 1, 1, 2 become the totals 1, 2, 4, and each value from 3 to 9 adds 4 to its tally of 0. Nine additions.

    why it is allowed: The total before it already holds every tally before it, so one addition makes each new total. The picture turns the tallies of 2, 0, 2, 1 into totals.

  3. the move: count the additions

    the line:
    A=1+1+⋯+1A = 1 + 1 + \dots + 1

    why it is allowed: AA is the totals added. By line 2, one for each value from 1 to 9, however many numbers there are.

  4. the move: add the ones

    the line:
    A=9A = 9

    why it is allowed: By line 3, nine ones. For 2 numbers or a million, still 9.

try it on small rows: over every order of 4 numbers, the average is A=9A = 9

Why does counting sort need n+10n + 10 places of extra memory?
  1. the move: list what it keeps

    the line:
    a second row of n places,and a tally for each valuefrom 0 to 9\begin{gathered} \text{a second row of } n \text{ places,} \\ \text{and a tally for each value} \\ \text{from 0 to 9} \end{gathered}

    why it is allowed: The numbers need nn more places. The site sends them into a second row; the Python keeps a copy of the row to read from the back. The ten tallies, later the totals, sit beside it. The few spare places for the number in hand are a fixed few, left out here.

  2. the move: add them

    the line:
    M=n+10M = n + 10

    why it is allowed: MM is the extra memory, by line 1. For 4 numbers, 14.

try it on small rows: over every order of 4 numbers, the average is M=14M = 14

How many counts, additions and placings in all, and how do they grow?
  1. the move: name every step

    the line:
    every step is a count,an addition or a placing\begin{gathered} \text{every step is a count,} \\ \text{an addition or a placing} \end{gathered}

    why it is allowed: TT counts these three kinds of step. Setting the ten tallies to 0 at the start is a fixed 10 more, left out, and the last moment only says the row is in order.

  2. the move: put in the three counts

    the line:
    T=n+9+nT = n + 9 + n

    why it is allowed: By line 1, with the counts worked out in the learn page's section 4, nn counts, 9 additions and nn placings.

  3. the move: gather

    the line:
    T=2n+9T = 2n + 9
    numberscountedadditionsplacedsteps
    449417
    889825
    121291233
    Every step for 4, 8 and 12 numbers. The 9 additions stay the same; the rest grow with the row.

    why it is allowed: By line 2, nn and nn make 2n2n. The table tries 4, 8 and 12 numbers.

  4. the move: a ceiling

    the line:
    T≤2n+9nT \le 2n + 9n

    why it is allowed: In line 3, from 1 number on, 9 is at most 9 times nn.

  5. the move: gather

    the line:
    T≤11nT \le 11n

    why it is allowed: By line 4, 2 times nn plus 9 times nn is 11n11n. At 1 number both sides are 11.

  6. the move: read it as a bound

    the line:
    T∈O(n)T \in O(n)

    why it is allowed: By line 5, TT is at most 11 times nn.

  7. the move: a floor

    the line:
    T≥2nT \ge 2n

    why it is allowed: In line 3, leaving out the 9 leaves less.

  8. the move: read it as a bound

    the line:
    T∈Ω(n)T \in \Omega(n)

    why it is allowed: By line 7, TT never drops below 2 times nn.

  9. the move: ceiling and floor together

    the line:
    T∈Θ(n)T \in \Theta(n)

    why it is allowed: Lines 6 and 8 bound TT by the same growth, nn.

try it with a small nn: at n=4n = 4, line 2 gives T=17T = 17, which you can work out by hand

count it yourself

Count every step on 2, 0, 2, 1. The first and last rows only start and finish; the 17 between are 4 counts, 9 additions and 4 placings, and 2 times 4, plus 9, is 17. Then check the placings against the formula.

2, 0, 2, 1, every step written down
stepthe rowwhat happenscountedtotals addedplaced
12, 0, 2, 1There are 4 numbers from 0 to 9. Start a tally of 0 for every value.2, 0, 2, 1000
22, 0, 2, 1Count 2: its tally is now 1.2, 0, 2, 1100
32, 0, 2, 1Count 0: its tally is now 1.2, 0, 2, 1200
42, 0, 2, 1Count 2: its tally is now 2.2, 0, 2, 1300
52, 0, 2, 1Count 1: its tally is now 1.2, 0, 2, 1400
62, 0, 2, 12 numbers are 1 or smaller.2, 0, 2, 1410
72, 0, 2, 14 numbers are 2 or smaller.2, 0, 2, 1420
82, 0, 2, 14 numbers are 3 or smaller.2, 0, 2, 1430
92, 0, 2, 14 numbers are 4 or smaller.2, 0, 2, 1440
102, 0, 2, 14 numbers are 5 or smaller.2, 0, 2, 1450
112, 0, 2, 14 numbers are 6 or smaller.2, 0, 2, 1460
122, 0, 2, 14 numbers are 7 or smaller.2, 0, 2, 1470
132, 0, 2, 14 numbers are 8 or smaller.2, 0, 2, 1480
142, 0, 2, 14 numbers are 9 or smaller.2, 0, 2, 1490
152, 1, 0, 2The total for 1 is 2, so 1 goes to place 2, and the total drops to 1.2, 1, 0, 2491
162, 1, 0, 2The total for 2 is 4, so 2 goes to place 4, and the total drops to 3.2, 1, 0, 2492
170, 1, 2, 2The total for 0 is 1, so 0 goes to place 1, and the total drops to 0.0, 1, 2, 2493
180, 1, 2, 2The total for 2 is 3, so 2 goes to place 3, and the total drops to 2.0, 1, 2, 2494
190, 1, 2, 2In order, without comparing two numbers: 4 numbers counted, 9 totals added and 4 numbers placed.0, 1, 2, 2494

In all, 4 placed. The formula from section 4, nn, gives P=4P = 4 at n=4n = 4: the same.

where you meet it

Counting goes around the sorting floor, since it never compares, as long as the numbers are small.

  • three.js, the 3D library this site loads

    three.js ships a radix sort among its add-ons, one this site does not use. It takes whole numbers kept as 32 bits, binary digits; each bit doubles the values, so 8 bits take 256. The sort counts the top 8 bits of each number into 256 tallies, makes the totals, and sends each number from the back, as counting sort does. Then it sorts each group the same way by the next 8 bits. A group of 32 numbers or fewer goes to insertion sort.

    source: three.js 0.186.1, examples/jsm/utils/SortUtils.js (radixSort, radixSortBlock, insertionSortBlock), as installed in this repository

  • radix sort

    The site's radix sort runs counting sort once for each digit, from the ones digit up. It relies on counting sort keeping equal digits in their order. It shares this page's tallies.

    source: the site's src/algorithms/ordering/radix-sort.ts and src/algorithms/shared/tally.ts; the books' volume one, chapter 12, its table of what each sorting method needs

  • exam marks

    The books sort eight exam papers marked out of 4 this way. Count each mark, make the running totals, place each paper: not one comparison.

    source: the books' volume one, chapter 12, 'when to reach for it'

what is used instead

When the numbers can be large, a comparing sort is used instead, or radix sort, a digit at a time. Numbers of 64 bits take 64 twos multiplied together. The books note that the tallies would then need about eighteen quintillion places, 18 followed by 18 zeros.

how it compares

Counting sort beside the other ways to put a row in order. It compares no two numbers, so it draws no line on the plot of comparisons.

comparisons on a shuffled row, on the log-log scales of section 2, one line for each way whose page is written
102104106108101010121014101102103104105106107bubble sortcocktail shaker sortinsertion sortselection sortshell sortquick sortrandomised quick sortmerge sortheap sort10110210310410510610710810910101011101210131014101102103104105106107bubble sortcocktail shaker sortinsertion sortselection sortshell sortquick sortrandomised quick sortmerge sortheap sort
  • bubble sort
  • cocktail shaker sort
  • insertion sort
  • selection sort
  • shell sort
  • quick sort
  • randomised quick sort
  • merge sort
  • heap sort
put a row in order: each way side by side
waybestaverageworstextra memorykeeps equal items in orderworks in placereach for it when
bubble sortΘ(n)\Theta(n)Θ(n2)\Theta(n^2)Θ(n2)\Theta(n^2)a few spare places (the walk number, the pair's place, whether the walk swapped, room for a number while two swap), the same however long the rowyesyesyou are learning how sorting works; for real work, insertion sort, which on every order of up to 8 different numbers makes no more comparisons, counted order by order
cocktail shaker sortΘ(n)\Theta(n)Θ(n2)\Theta(n^2)Θ(n2)\Theta(n^2)a few spare places, the same however long the rowyesyesyou are learning how sorting works; for real work, insertion sort
insertion sortΘ(n)\Theta(n)Θ(n2)\Theta(n^2)Θ(n2)\Theta(n^2)room for a few numbers (the number being placed, where its slide has reached, which number is next), the same however long the rowyesyesthe row is short, a few dozen numbers, or nearly in order
selection sortΘ(n2)\Theta(n^2)Θ(n2)\Theta(n^2)Θ(n2)\Theta(n^2)room for a few numbers (the place being filled, where the smallest so far stands, the number looked at, one held during a swap), the same however long the rownoyesmoving a number costs far more than comparing two, and the row is short
shell sortΘ(n log⁡2 n)\Theta(n \,\log_2\, n)not known; between Ω(n log⁡2 n)\Omega(n \,\log_2\, n) and O(n2)O(n^2)not worked out here; between Ω(n log⁡2 n)\Omega(n \,\log_2\, n) and O(n2)O(n^2)a few spare places (the gap, the number picked up, its place), the same however long the rownoyesyou want a few lines of code and no room beyond the row. On this site's shuffles of 200 to 10,000 numbers it averaged under a fifth of insertion sort's comparisons
quick sortΘ(n log⁡2 n)\Theta(n \,\log_2\, n)Θ(n log⁡2 n)\Theta(n \,\log_2\, n)Θ(n2)\Theta(n^2)a list of the parts still to sort, two memory places each. That is two places for each number on a row in order, and far fewer on a shuffle, about 51 for 100,000 numbers. So this plain version does not work in place, as its spare room grows with the rownonoyou want a fast sort on shuffled rows with no second row, and equal items need not keep their order; use a version with a random or middle pivot
randomised quick sortat most O(n log⁡2 n)O(n \,\log_2\, n), as every row of different numbers averages that over the picks; a row with equal numbers can cost a little lessΘ(n log⁡2 n)\Theta(n \,\log_2\, n)Θ(n2)\Theta(n^2), a row of equal numbers, whatever the picks; no run costs more, since a pair meets at most oncea list of the parts waiting to be sorted, each kept as its first and last place. On average far shorter than the row, about 66 places for a million numbers. Unlucky picks can make it grow with the rownonoyou want quick sort without a dear row in order, and equal items need not keep their order
merge sortΘ(n log⁡2 n)\Theta(n \,\log_2\, n)Θ(n log⁡2 n)\Theta(n \,\log_2\, n)Θ(n log⁡2 n)\Theta(n \,\log_2\, n)a second row as long as the rowyesnoyou need comparisons growing no faster than n log⁡2 nn \,\log_2\, n on every row, equal items kept in order, or a file too big for memory sorted
heap sortΘ(n)\Theta(n), every number the sameΘ(n log⁡2 n)\Theta(n \,\log_2\, n), shuffled; measured, no formula worked out hereΘ(n log⁡2 n)\Theta(n \,\log_2\, n), the dearest row; this page finds it only for short rows, by trying every ordera few places, however long the rownoyesyou need a sort with no slow row and no second row, and equal items need not keep their order
counting sortΘ(n)\Theta(n) steps, every row alikeΘ(n)\Theta(n) stepsΘ(n)\Theta(n) steps, every row alikea second row of n places and 10 talliesyesnothe numbers are small whole numbers, such as ratings from 0 to 9, and equal ones must keep their order
radix sortΘ(n)\Theta(n) placings, every number below 10Θ(n)\Theta(n) placings, between the best and the worst, as every order costs the sameΘ(n)\Theta(n) placings, three passes for numbers up to 999a second row of n places and 10 talliesyesnomany whole numbers with few digits, such as numbers from 0 to 999
extra memory:
the room it needs on top of the input itself, while it runs.
keeps equal items in order:
people sorted by age keep the order they arrived in within each age; in general, two items equal in what is being sorted come out in the order they went in.
works in place:
it rearranges the input where it stands, with only a few spare places, rather than building a copy; a different sense from a number being in place, in its final position.

race them on one row of your own