Good, better, best. Never let it rest.

PHP实现计数排序

粘贴代码如下:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
计数排序:
function countingSort($arr)
{
$maxValue = max($arr);

// 初始化数组
for ($i=0; $i < $maxValue+1; $i++) {
$bucket[$i] = 0;
}

// 写入临时数组
for ($i=0; $i < count($arr); $i++) {
$bucket[$arr[$i]]++;
}

// 覆盖原数组
$index = 0;
for ($i=0; $i < $maxValue+1; $i++) {
while($bucket[$i] > 0) {
$arr[$index++] = $i;
$bucket[$i]--;
}
}

return $arr;
}