Counting sort
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.
step 2 of 27
Count 4: its tally is now 1.
what it remembers to know where it is
- number
- 4
- tally
- 1
step 9 of 27
Count 4: its tally is now 2.
what it remembers to know where it is
- number
- 4
- tally
- 2
step 18 of 27
8 numbers are 9 or smaller.
what it remembers to know where it is
- number
- 9
- tally
- 8
step 19 of 27
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
step 23 of 27
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
step 25 of 27
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
step 27 of 27
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.
the steps, in plain words
choose a step to mark the Python, a programming language, that does it
- start a tally of 0 for every value from 0 to 9Python line 10
- count each number into the tally for its valuePython lines 11 and 12
- add each tally to the ones before it: now it says how many numbers are that value or smallerPython lines 14 and 15
- 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 numbers places exactly , so the points sit on the line.
placed, ten times more at each mark up
, 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
| placed | time | |
|---|---|---|
| 1,000 | 1,000 | about 1 microsecond |
| 100,000 | 100,000 | about 100 microseconds |
| 10,000,000 | 10,000,000 | about 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
, 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.
| averageevery row, whatever its order | |
|---|---|
| counted | |
| totals added | |
| placed | |
| how the placed grow in each case | |
| tight, | |
| ceiling, | |
| floor, | |
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.
| row | counted | additions | placed |
|---|---|---|---|
| 0, 1, 2, 3, 5, 6, 7, 8 | 8 | 9 | 8 |
| 8, 7, 6, 5, 3, 2, 1, 0 | 8 | 9 | 8 |
| 4, 1, 3, 1, 0, 3, 2, 4 | 8 | 9 | 8 |
where the formula comes from
Each count above, worked out in small steps, each naming the line it comes from.
the move: see the last pass
the line: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.
the move: one for each number
the line:why it is allowed: is the numbers placed. By line 1, one placing for each of the numbers.
guess it, thenthe move: add the ones
the line:why it is allowed: By line 2, ones add up to . For 2, 0, 2, 1, that is 4.
guess it, thenthe move: any row
the line: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.
guess it, thenthe move: a ceiling
the line:why it is allowed: By line 3, is , so it is at most .
guess it, thenthe move: read it as a bound
the line:why it is allowed: By line 5, is at most 1 times .
guess it, thenthe move: a floor
the line:why it is allowed: By line 3, is at least too.
guess it, thenthe move: read it as a bound
the line:why it is allowed: By line 7, never drops below 1 times .
guess it, thenthe move: ceiling and floor together
the line:why it is allowed: Lines 6 and 8 bound by the same growth, .
guess it, then
try it on small rows: over every order of 4 numbers, the average is
the move: see the first pass
the line: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.
the move: one for each number
the line:why it is allowed: is the numbers counted. By line 1, one count for each of the numbers.
guess it, thenthe move: add the ones
the line:why it is allowed: By line 2, ones add up to . For 2, 0, 2, 1, that is 4.
guess it, then
try it on small rows: over every order of 4 numbers, the average is
the move: the first total
the line:why it is allowed: No value is below 0, so nothing is added to it.
the move: one addition for each value after it
the line: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.
guess it, thenthe move: count the additions
the line:why it is allowed: is the totals added. By line 2, one for each value from 1 to 9, however many numbers there are.
guess it, thenthe move: add the ones
the line:why it is allowed: By line 3, nine ones. For 2 numbers or a million, still 9.
guess it, then
try it on small rows: over every order of 4 numbers, the average is
the move: list what it keeps
the line:why it is allowed: The numbers need 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.
the move: add them
the line:why it is allowed: is the extra memory, by line 1. For 4 numbers, 14.
guess it, then
try it on small rows: over every order of 4 numbers, the average is
the move: name every step
the line:why it is allowed: 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.
the move: put in the three counts
the line:why it is allowed: By line 1, with the counts worked out in the learn page's section 4, counts, 9 additions and placings.
guess it, thenthe move: gather
the line:numbers counted additions placed steps 4 4 9 4 17 8 8 9 8 25 12 12 9 12 33 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, and make . The table tries 4, 8 and 12 numbers.
guess it, thenthe move: a ceiling
the line:why it is allowed: In line 3, from 1 number on, 9 is at most 9 times .
guess it, thenthe move: gather
the line:why it is allowed: By line 4, 2 times plus 9 times is . At 1 number both sides are 11.
guess it, thenthe move: read it as a bound
the line:why it is allowed: By line 5, is at most 11 times .
guess it, thenthe move: a floor
the line:why it is allowed: In line 3, leaving out the 9 leaves less.
guess it, thenthe move: read it as a bound
the line:why it is allowed: By line 7, never drops below 2 times .
guess it, thenthe move: ceiling and floor together
the line:why it is allowed: Lines 6 and 8 bound by the same growth, .
guess it, then
try it with a small : at , line 2 gives , 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.
| step | the row | what happens | counted | totals added | placed |
|---|---|---|---|---|---|
| 1 | 2, 0, 2, 1 | There are 4 numbers from 0 to 9. Start a tally of 0 for every value.2, 0, 2, 1 | 0 | 0 | 0 |
| 2 | 2, 0, 2, 1 | Count 2: its tally is now 1.2, 0, 2, 1 | 1 | 0 | 0 |
| 3 | 2, 0, 2, 1 | Count 0: its tally is now 1.2, 0, 2, 1 | 2 | 0 | 0 |
| 4 | 2, 0, 2, 1 | Count 2: its tally is now 2.2, 0, 2, 1 | 3 | 0 | 0 |
| 5 | 2, 0, 2, 1 | Count 1: its tally is now 1.2, 0, 2, 1 | 4 | 0 | 0 |
| 6 | 2, 0, 2, 1 | 2 numbers are 1 or smaller.2, 0, 2, 1 | 4 | 1 | 0 |
| 7 | 2, 0, 2, 1 | 4 numbers are 2 or smaller.2, 0, 2, 1 | 4 | 2 | 0 |
| 8 | 2, 0, 2, 1 | 4 numbers are 3 or smaller.2, 0, 2, 1 | 4 | 3 | 0 |
| 9 | 2, 0, 2, 1 | 4 numbers are 4 or smaller.2, 0, 2, 1 | 4 | 4 | 0 |
| 10 | 2, 0, 2, 1 | 4 numbers are 5 or smaller.2, 0, 2, 1 | 4 | 5 | 0 |
| 11 | 2, 0, 2, 1 | 4 numbers are 6 or smaller.2, 0, 2, 1 | 4 | 6 | 0 |
| 12 | 2, 0, 2, 1 | 4 numbers are 7 or smaller.2, 0, 2, 1 | 4 | 7 | 0 |
| 13 | 2, 0, 2, 1 | 4 numbers are 8 or smaller.2, 0, 2, 1 | 4 | 8 | 0 |
| 14 | 2, 0, 2, 1 | 4 numbers are 9 or smaller.2, 0, 2, 1 | 4 | 9 | 0 |
| 15 | 2, 1, 0, 2 | The total for 1 is 2, so 1 goes to place 2, and the total drops to 1.2, 1, 0, 2 | 4 | 9 | 1 |
| 16 | 2, 1, 0, 2 | The total for 2 is 4, so 2 goes to place 4, and the total drops to 3.2, 1, 0, 2 | 4 | 9 | 2 |
| 17 | 0, 1, 2, 2 | The total for 0 is 1, so 0 goes to place 1, and the total drops to 0.0, 1, 2, 2 | 4 | 9 | 3 |
| 18 | 0, 1, 2, 2 | The total for 2 is 3, so 2 goes to place 3, and the total drops to 2.0, 1, 2, 2 | 4 | 9 | 4 |
| 19 | 0, 1, 2, 2 | In order, without comparing two numbers: 4 numbers counted, 9 totals added and 4 numbers placed.0, 1, 2, 2 | 4 | 9 | 4 |
In all, 4 placed. The formula from section 4, , gives at : 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.
- bubble sort
- cocktail shaker sort
- insertion sort
- selection sort
- shell sort
- quick sort
- randomised quick sort
- merge sort
- heap sort
| way | best | average | worst | extra memory | keeps equal items in order | works in place | reach for it when |
|---|---|---|---|---|---|---|---|
| bubble sort | 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 row | yes | yes | you 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 | a few spare places, the same however long the row | yes | yes | you are learning how sorting works; for real work, insertion sort | |||
| insertion sort | room for a few numbers (the number being placed, where its slide has reached, which number is next), the same however long the row | yes | yes | the row is short, a few dozen numbers, or nearly in order | |||
| selection sort | 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 row | no | yes | moving a number costs far more than comparing two, and the row is short | |||
| shell sort | not known; between and | not worked out here; between and | a few spare places (the gap, the number picked up, its place), the same however long the row | no | yes | you 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 | 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 row | no | no | you 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 sort | at most , as every row of different numbers averages that over the picks; a row with equal numbers can cost a little less | , a row of equal numbers, whatever the picks; no run costs more, since a pair meets at most once | a 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 row | no | no | you want quick sort without a dear row in order, and equal items need not keep their order | |
| merge sort | a second row as long as the row | yes | no | you need comparisons growing no faster than on every row, equal items kept in order, or a file too big for memory sorted | |||
| heap sort | , every number the same | , shuffled; measured, no formula worked out here | , the dearest row; this page finds it only for short rows, by trying every order | a few places, however long the row | no | yes | you need a sort with no slow row and no second row, and equal items need not keep their order |
| counting sort | steps, every row alike | steps | steps, every row alike | a second row of n places and 10 tallies | yes | no | the numbers are small whole numbers, such as ratings from 0 to 9, and equal ones must keep their order |
| radix sort | placings, every number below 10 | placings, between the best and the worst, as every order costs the same | placings, three passes for numbers up to 999 | a second row of n places and 10 tallies | yes | no | many 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.