This Counting Sort lesson is for a beginner. Read the short notes, run each example, then change one name or number and run it again.
Counting sort counts how many times each small integer appears, then writes the values back in order.
It needs integers from zero up to a known maximum. It is the wrong tool for text or for huge ranges.
Example 1: Start here
The values must be zero or positive.
def counting(items): # define the function; it runs when you call it
counts = [0] * (max(items) + 1) # a list; the values stay in this order
for n in items: # repeat the indented lines once per value
counts[n] += 1 # update the stored value
out = [] # a list; the values stay in this order
for n, count in enumerate(counts): # repeat the indented lines once per value
out.extend([n] * count)
return out # send this value back to the caller
print(counting([4, 1, 3, 1]))
Example 2: Walk the values
Counting Sort starts by visiting one value at a time. Read the printed lines from top to bottom.
values = [16, 3, 11, 7] # a list; the values stay in this order
for value in values: # repeat the indented lines once per value
print(value)
Example 3: Keep the largest
Many data-structure lessons reduce a list to one answer. This one remembers the largest number seen so far.
values = [16, 3, 11, 7] # a list; the values stay in this order
best = values[0] # the first value
for value in values: # repeat the indented lines once per value
if value > best: # run the indented lines only when this is true
best = value # another name for the same value
print(best)
Example 4: Search for a target
A search asks one yes-or-no question: is the target in the collection? Counting Sort builds on that question.
values = [3, 16, 11] # a list; the values stay in this order
target = 16 # a whole number
print(target in values) # in is True when the value is found
