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.
Code
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
JSON SorterSort JSON object keys by code point ascending or descending, recursively or top-level only, preserving array order.Line SorterSort text lines ascending or descending with numeric-aware ordering, duplicate removal, empty-line filtering, and locale-aware comparison.SemVer SorterParse and sort Semantic Version 2.0.0 strings with prerelease and build metadata, respecting prerelease-below-release precedence.SRI Hash GeneratorGenerate Subresource Integrity (SRI) hashes from resource content using SHA-256, SHA-384, or SHA-512, and copy a ready-to-use script tag.
FAQ
- Are there dependencies to manage?
- No. There are no dependencies to declare or install. The file defines `counting_sort` at load time.
Report a problem with this exampleOpens a pre-filled issue on GitHub.