ZetCode

PHP Counting Sort Algorithm

last modified November 25, 2026

Counting sort orders integers by counting how often each value occurs, then writing the values back in key order. It makes no comparisons, so it can run in O(n + k) time, where n is the number of elements and k is the width of the value range.

This article builds the algorithm in PHP: counting occurrences, reconstructing the array, handling negative values, making the sort stable for records, reversing the order, and deciding when the technique is worth its memory.

How counting sort works

The algorithm needs a counter for every possible value between the smallest and the largest. The first pass reads the input and increments the counter for each value. The second pass walks the counters from the smallest value to the largest and appends each value as many times as its counter says.

No two elements are ever compared. The position of a value follows from its numeric key, which is why the running time depends on the range rather than on sorting comparisons. A comparison sort needs at least n log n comparisons in the general case; counting sort replaces them with a table lookup.

The cost is memory: the counter table has k entries, so a range much wider than the input wastes both time and memory. The simple version also writes plain values, so equal elements lose their identity. Adding prefix sums and writing each element to the next free slot of its key preserves the input order and makes the sort stable.

Counting occurrences

The first example performs only the counting pass. It builds a table from 0 to the largest value and prints every counter.

counting_count.php
<?php

declare(strict_types=1);

$values = [4, 2, 2, 8, 3, 1];

$counts = array_fill(0, max($values) + 1, 0);

foreach ($values as $value) {
    $counts[$value]++;
}

foreach ($counts as $value => $count) {
    echo $value, ": ", $count, "\n";
}

array_fill(0, max($values) + 1, 0) creates one zero counter per value from 0 to 8. The loop then increments the slot named by each value, so 2 appears twice and 5, 6, and 7 not at all. A counter of zero still occupies a slot: the table covers the whole range, not just the values that occur.

$ php counting_count.php
0: 0
1: 1
2: 2
3: 1
4: 1
5: 0
6: 0
7: 0
8: 1

Building the sorted array

The second pass walks the counters in order and appends each value as many times as it was counted. Appending in ascending key order produces an ascending array.

counting_sort.php
<?php

declare(strict_types=1);

function countingSort(array $values): array
{
    $counts = array_fill(0, max($values) + 1, 0);

    foreach ($values as $value) {
        $counts[$value]++;
    }

    $sorted = [];

    foreach ($counts as $value => $count) {
        for ($i = 0; $i < $count; $i++) {
            $sorted[] = $value;
        }
    }

    return $sorted;
}

$values = [4, 2, 2, 8, 3, 1];
echo implode(", ", countingSort($values)), "\n";

The outer loop visits 0, 1, 2, and so on, and the inner loop repeats the current value $count times. Because the counters are read in ascending order, the result is ascending without a single comparison. The function assumes a non-empty array; max() raises a ValueError on an empty one, so production code checks for that first.

$ php counting_sort.php
1, 2, 2, 3, 4, 8

Negative values and the offset

An array index cannot be negative, so values below zero need an offset. Subtracting the minimum maps the smallest value to index 0 and shifts the whole range into non-negative territory.

counting_negative.php
<?php

declare(strict_types=1);

function countingSort(array $values): array
{
    $min = min($values);
    $max = max($values);
    $range = $max - $min + 1;

    $counts = array_fill(0, $range, 0);

    foreach ($values as $value) {
        $counts[$value - $min]++;
    }

    $sorted = [];

    foreach ($counts as $offset => $count) {
        for ($i = 0; $i < $count; $i++) {
            $sorted[] = $offset + $min;
        }
    }

    return $sorted;
}

$values = [-5, 2, -3, 8, 0, -1, 2];
echo implode(", ", countingSort($values)), "\n";

$counts[$value - $min] stores the count for $value, and $offset + $min converts the index back to the original number while rebuilding. With a minimum of -5, the value -3 lands in slot 2. The same offset also compresses a range that does not start at zero, so [1000, 1001] needs two counters rather than a thousand.

$ php counting_negative.php
-5, -3, -1, 0, 2, 2, 8

A stable sort for records

Sorting records by a key is where stability matters: two records with the same key should keep their original order. The next version converts the counters into starting positions and writes each record to the next free slot for its key.

counting_stable.php
<?php

declare(strict_types=1);

function countingSortBy(array $items, callable $key): array
{
    $keys = array_map($key, $items);
    $min = min($keys);
    $max = max($keys);

    $positions = array_fill(0, $max - $min + 1, 0);

    foreach ($keys as $value) {
        $positions[$value - $min]++;
    }

    $total = 0;

    foreach ($positions as $index => $count) {
        $positions[$index] = $total;
        $total += $count;
    }

    $sorted = [];

    foreach ($items as $index => $item) {
        $slot = $positions[$keys[$index] - $min]++;
        $sorted[$slot] = $item;
    }

    ksort($sorted);
    return $sorted;
}

$people = [
    ["name" => "Alice", "score" => 90],
    ["name" => "Bob", "score" => 75],
    ["name" => "Cara", "score" => 90],
    ["name" => "Dan", "score" => 75],
];

foreach (countingSortBy($people, fn(array $p) => $p["score"]) as $person) {
    echo $person["name"], " (", $person["score"], ")\n";
}

The first loop counts the keys. The second turns each count into a prefix sum, so $positions[$key] is the first output slot for that key. The final loop walks the records in their original order and places each one at the next free slot, incrementing that slot. Bob and Dan both score 75 and appear in that order; Alice and Cara both score 90 and keep theirs. ksort() restores the numeric order of the slots before printing.

$ php counting_stable.php
Bob (75)
Dan (75)
Alice (90)
Cara (90)

Descending order

The direction is a property of the reconstruction pass, not of the counting. Walking the counters from the largest key down produces a descending array.

counting_desc.php
<?php

declare(strict_types=1);

function countingSortDesc(array $values): array
{
    $counts = array_fill(0, max($values) + 1, 0);

    foreach ($values as $value) {
        $counts[$value]++;
    }

    $sorted = [];

    foreach (array_reverse($counts, true) as $value => $count) {
        for ($i = 0; $i < $count; $i++) {
            $sorted[] = $value;
        }
    }

    return $sorted;
}

$values = [4, 2, 2, 8, 3, 1];
echo implode(", ", countingSortDesc($values)), "\n";

array_reverse($counts, true) keeps the keys, so the loop still knows which value each counter belongs to. The counting pass is unchanged and the time complexity stays O(n + k). A generic version would take the direction as an argument instead of duplicating the function.

$ php counting_desc.php
8, 4, 3, 2, 2, 1

The range, not the count

The size of the counter table is decided by the spread of the values, not by how many values there are. The next example compares three inputs of similar length.

counting_range.php
<?php

declare(strict_types=1);

$cases = [
    "dense" => [4, 5, 6, 7, 8],
    "clustered" => [1000, 1001, 1002, 1003, 1004],
    "wide" => [0, 500, 1000],
];

foreach ($cases as $label => $values) {
    $range = max($values) - min($values) + 1;
    echo $label, ": ", count($values), " values, ", $range, " counters\n";
}

The dense and clustered inputs need five counters each, even though the clustered values are around 1000, because the offset removes the gap below them. The wide input needs 1001 counters for only three values. This is the trade-off in one line: a compact range is cheap, a scattered range is not.

$ php counting_range.php
dense: 5 values, 5 counters
clustered: 5 values, 5 counters
wide: 3 values, 1001 counters

When to use counting sort

Counting sort is a good fit when the keys are integers with a known, narrow range and when linear time matters more than generality.

The limitations follow from the same design. The keys must be integers or mappable to integers, the extra memory is O(k), and a wide range makes both passes slow. For everyday PHP data, sort() and usort() are implemented in C and are usually faster; reach for counting sort when the range is genuinely small and the asymptotic advantage is real.

Source

Wikipedia: counting sort

PHP manual: array_fill

PHP manual: array_reverse

This article implemented counting sort in PHP: the counting pass, the reconstruction, negative values with an offset, a stable version for records, descending order, and the effect of the value range. Continue with PHP radix sort, which applies counting sort digit by digit, or compare it with merge sort and quick sort.

Author

I am Jan Bodnar, a programmer and technical writer. I have been writing programming tutorials at ZetCode since 2007 and have published eight e-books. See about the author.

List all PHP tutorials.