Counting Sort

Sort an array of non-negative integers using counting sort for linear time performance.

Code

Algorithms
$count = array_fill(0, max($arr) + 1, 0);
foreach ($arr as $x) $count[$x]++;
$result = [];
foreach ($count as $i => $c) {
    for ($j = 0; $j < $c; $j++) $result[] = $i;
}
$result;

Parameters

Array of integers

Server

More PHP Snippets