Sort small integer keys in linear time and keep equal items in order.
Counting sort turns key counts into start places, so each item goes to its final place, and a left-to-right pass keeps equal keys in order.
Use it when the keys are whole numbers in a small known range, or can be cut into small digits. Signal words: ratings, ages, scores, digits, fixed-width codes, equal keys keep their order.
Start: one counter for each possible key, all zero.
Step: count every key. Turn the counts into start places. Place each item, from left to right, at its key's free place and move that place up by 1. For radix sort, repeat this for each digit, from the last digit to the first.
Stop: when every item is placed. For radix sort, stop after the digit of the largest value.
It does not compare keys, so it needs a small key range, and it needs a second list for the output.
Cost: O(n + k) time and space for n items and k possible keys. Radix sort costs O(d × (n + b)) for d digits in base b.
def counting_sort(values, limit):
# [1] One counter for each possible key, all zero.
counts = [0] * limit
# [2] Count how many times each key occurs.
for value in values:
counts[value] += 1
# [3] Write each key out as many times as it was counted, from the smallest key up.
result = []
for key in range(limit):
result.extend([key] * counts[key])
return resultpublic int[] countingSort(int[] values, int limit) {
// [1] One counter for each possible key, all zero.
int[] counts = new int[limit];
// [2] Count how many times each key occurs.
for (int value : values) {
counts[value]++;
}
// [3] Write each key out as many times as it was counted, from the smallest key up.
int[] result = new int[values.length];
int place = 0;
for (int key = 0; key < limit; key++) {
for (int c = 0; c < counts[key]; c++) {
result[place++] = key;
}
}
return result;
}vector<int> countingSort(const vector<int>& values, int limit) {
// [1] One counter for each possible key, all zero.
vector<int> counts(limit, 0);
// [2] Count how many times each key occurs.
for (int value : values) {
counts[value]++;
}
// [3] Write each key out as many times as it was counted, from the smallest key up.
vector<int> result;
for (int key = 0; key < limit; key++) {
for (int c = 0; c < counts[key]; c++) {
result.push_back(key);
}
}
return result;
}function countingSort(values, limit) {
// [1] One counter for each possible key, all zero.
const counts = new Array(limit).fill(0);
// [2] Count how many times each key occurs.
for (const value of values) {
counts[value]++;
}
// [3] Write each key out as many times as it was counted, from the smallest key up.
const result = [];
for (let key = 0; key < limit; key++) {
for (let c = 0; c < counts[key]; c++) {
result.push(key);
}
}
return result;
}def stable_order(keys, limit):
# [1] One counter for each possible key, then count the keys.
counts = [0] * limit
for key in keys:
counts[key] += 1
# [2] Turn the counts into start places: the first place for each key.
starts = [0] * limit
total = 0
for key in range(limit):
starts[key] = total
total += counts[key]
# [3] Place every index in input order, at its key's next free place.
order = [0] * len(keys)
for i, key in enumerate(keys):
order[starts[key]] = i
starts[key] += 1
# [4] Return the order of original indices.
return orderpublic int[] stableOrder(int[] keys, int limit) {
// [1] One counter for each possible key, then count the keys.
int[] counts = new int[limit];
for (int key : keys) {
counts[key]++;
}
// [2] Turn the counts into start places: the first place for each key.
int[] starts = new int[limit];
int total = 0;
for (int key = 0; key < limit; key++) {
starts[key] = total;
total += counts[key];
}
// [3] Place every index in input order, at its key's next free place.
int[] order = new int[keys.length];
for (int i = 0; i < keys.length; i++) {
order[starts[keys[i]]] = i;
starts[keys[i]]++;
}
// [4] Return the order of original indices.
return order;
}vector<int> stableOrder(const vector<int>& keys, int limit) {
// [1] One counter for each possible key, then count the keys.
vector<int> counts(limit, 0);
for (int key : keys) {
counts[key]++;
}
// [2] Turn the counts into start places: the first place for each key.
vector<int> starts(limit, 0);
int total = 0;
for (int key = 0; key < limit; key++) {
starts[key] = total;
total += counts[key];
}
// [3] Place every index in input order, at its key's next free place.
vector<int> order(keys.size());
for (int i = 0; i < (int)keys.size(); i++) {
order[starts[keys[i]]] = i;
starts[keys[i]]++;
}
// [4] Return the order of original indices.
return order;
}function stableOrder(keys, limit) {
// [1] One counter for each possible key, then count the keys.
const counts = new Array(limit).fill(0);
for (const key of keys) {
counts[key]++;
}
// [2] Turn the counts into start places: the first place for each key.
const starts = new Array(limit).fill(0);
let total = 0;
for (let key = 0; key < limit; key++) {
starts[key] = total;
total += counts[key];
}
// [3] Place every index in input order, at its key's next free place.
const order = new Array(keys.length);
for (let i = 0; i < keys.length; i++) {
order[starts[keys[i]]] = i;
starts[keys[i]]++;
}
// [4] Return the order of original indices.
return order;
}def radix_sort(values):
items = list(values)
if not items:
return items
# [1] The number of passes is the number of digits of the largest value.
biggest = max(items)
place = 1
while biggest // place > 0:
# [2] Sort by this digit with a stable counting sort, so earlier passes survive on ties.
counts = [0] * 10
for value in items:
counts[(value // place) % 10] += 1
starts = [0] * 10
total = 0
for digit in range(10):
starts[digit] = total
total += counts[digit]
result = [0] * len(items)
for value in items:
digit = (value // place) % 10
result[starts[digit]] = value
starts[digit] += 1
items = result
# [3] Move to the next higher digit.
place *= 10
# [4] Return the sorted values.
return itemspublic int[] radixSort(int[] values) {
int[] items = values.clone();
if (items.length == 0) {
return items;
}
// [1] The number of passes is the number of digits of the largest value.
int biggest = 0;
for (int value : items) {
biggest = Math.max(biggest, value);
}
long place = 1;
while (biggest / place > 0) {
// [2] Sort by this digit with a stable counting sort, so earlier passes survive on ties.
int[] counts = new int[10];
for (int value : items) {
counts[(int) ((value / place) % 10)]++;
}
int[] starts = new int[10];
int total = 0;
for (int digit = 0; digit < 10; digit++) {
starts[digit] = total;
total += counts[digit];
}
int[] result = new int[items.length];
for (int value : items) {
int digit = (int) ((value / place) % 10);
result[starts[digit]] = value;
starts[digit]++;
}
items = result;
// [3] Move to the next higher digit.
place *= 10;
}
// [4] Return the sorted values.
return items;
}vector<int> radixSort(const vector<int>& values) {
vector<int> items = values;
if (items.empty()) {
return items;
}
// [1] The number of passes is the number of digits of the largest value.
int biggest = *max_element(items.begin(), items.end());
long long place = 1;
while (biggest / place > 0) {
// [2] Sort by this digit with a stable counting sort, so earlier passes survive on ties.
vector<int> counts(10, 0);
for (int value : items) {
counts[(value / place) % 10]++;
}
vector<int> starts(10, 0);
int total = 0;
for (int digit = 0; digit < 10; digit++) {
starts[digit] = total;
total += counts[digit];
}
vector<int> result(items.size());
for (int value : items) {
int digit = (value / place) % 10;
result[starts[digit]] = value;
starts[digit]++;
}
items = result;
// [3] Move to the next higher digit.
place *= 10;
}
// [4] Return the sorted values.
return items;
}function radixSort(values) {
let items = [...values];
if (items.length === 0) {
return items;
}
// [1] The number of passes is the number of digits of the largest value.
const biggest = Math.max(...items);
let place = 1;
while (Math.floor(biggest / place) > 0) {
// [2] Sort by this digit with a stable counting sort, so earlier passes survive on ties.
const counts = new Array(10).fill(0);
for (const value of items) {
counts[Math.floor(value / place) % 10]++;
}
const starts = new Array(10).fill(0);
let total = 0;
for (let digit = 0; digit < 10; digit++) {
starts[digit] = total;
total += counts[digit];
}
const result = new Array(items.length);
for (const value of items) {
const digit = Math.floor(value / place) % 10;
result[starts[digit]] = value;
starts[digit]++;
}
items = result;
// [3] Move to the next higher digit.
place *= 10;
}
// [4] Return the sorted values.
return items;
}This version reads the plays from the last to the first and fills each block from its start. The order is sorted by rating, but equal ratings are reversed.
This version makes the counter array as long as the number of items, because "n counters is enough".
This version runs the stable passes from the first digit to the last. The last pass then decides the whole order.
This version uses the right-to-left placing of Exhibit 1 for each digit. A pass then reverses items whose digit is equal, and it destroys the work of earlier passes.
A review service sorts 1,000 account numbers, each up to 10^9. A counting sort needs 1,000,000,001 counters, which is 4,000,000,004 bytes at 4 bytes each. Merge sort on 1,000 random distinct numbers made 8,717 comparisons.
systemdesignmastery.dev/dsa/cheatsheets/counting-sort-and-stability