计数排序Php代码貌似不准确
ttttonyhe opened this issue · 1 comments
ttttonyhe commented
计数排序 实例代码
function countingSort($arr, $maxValue = null)
{
if ($maxValue === null) {
$maxValue = max($arr);
}
for ($m = 0; $m < $maxValue + 1; $m++) {
$bucket[] = null;
}
$arrLen = count($arr);
for ($i = 0; $i < $arrLen; $i++) {
if (!array_key_exists($arr[$i], $bucket)) {
$bucket[$arr[$i]] = 0;
}
$bucket[$arr[$i]]++;
}
$sortedIndex = 0;
foreach ($bucket as $key => $len) {
if ($len !== null) $arr[$sortedIndex++] = $key; //此步将不能确保重复值在原数组中改变位置
}
return $arr;
}注释行应该可以用以下代码替换解决此问题:
if($len !== null){
for($j = 0; $j < $len; $j++){
$arr[$sortedIndex++] = $key;
}
}hustcc commented
可以帮忙 pr 代码进来!