Counting Sort Places Values Without Comparing

Tallying occurrences into a counts array replays values in order with zero pairwise comparisons, in O(n + max_value) time for small known ranges.

PythonData Integrity

Code

pythonsnippet
20 lines
def counting_sort(values, max_value):
    """Sort small non-negative integers without any pairwise comparisons."""
    # counts[v] = how many times v appeared: O(n + max_value) overall.
    counts = [0] * (max_value + 1)
    for value in values:
        counts[value] += 1

    # Replay each value count[v] times. Equal keys lose their original
    # order, so this plain variant suits bare ints, not records.
    sorted_values = []
    for value, count in enumerate(counts):
        sorted_values.extend([value] * count)
    return sorted_values

scores = [3, 1, 4, 1, 5, 9, 2, 6, 5, 3]
print("scores:", scores)
print("sorted:", counting_sort(scores, 9))

ages = [0, 2, 2, 1, 0]
print("ages  :", ages, "->", counting_sort(ages, 2))

Output

Captured from a sandboxed run of this snippet in the build pipeline.

scores: [3, 1, 4, 1, 5, 9, 2, 6, 5, 3]
sorted: [1, 1, 2, 3, 3, 4, 5, 5, 6, 9]
ages  : [0, 2, 2, 1, 0] -> [0, 0, 1, 2, 2]

How it works

Counting Sort Places Values Without Comparing is built around the function counting_sort.

Iteration happens inside for value in values — everything outside it runs once.

What to watch for

  • No external packages — everything relies on the language’s built-in APIs.

Using it

Entry signature: def counting_sort(values, max_value)

Running the file prints labeled results such as scores:, sorted:, ages : — each operation’s effect is visible in the output.

counting_sort is the public entry point; everything else in the file exists to support it.

Interactive Tools for This Topic

FAQ

Are there dependencies to manage?
No. There are no dependencies to declare or install. The file defines `counting_sort` at load time.