Home >Backend Development >PHP Tutorial >How to implement counting sorting code in PHP
This article introduces to you the code on how to implement counting sorting in PHP. It has certain reference value. Friends in need can refer to it. I hope it will be helpful to you.
/** * 计数排序: 桶排序的一种 */ $arr = [5,69,4,32,14,8,74,95,23,56,41,5,31,63]; // include 'data.php'; $length = count($arr); $maxValue = $arr[0]; // 找出数组中的最大值 for ($i=1; $i < $length; $i++) { if ($arr[$i] > $maxValue) { $maxValue = $arr[$i]; } } /** * 定长数组, 键会自动排序, PHP数组是hash表的实现, * 如果这里用普通的数组, 键不会自动排序, 不存在的键也不会自动填充null */ $frequency = new SplFixedArray($maxValue + 1); /** * 统计arr中, 值出现的频次 */ for ($i=0; $i < $length; $i++) { if(empty($frequency[$arr[$i]])) $frequency[$arr[$i]] = 0; $frequency[$arr[$i]] += 1; } // 清空$arr $arr = []; // 遍历frequency, 如果其元素有值, 那么将键push到arr中 for ($i=0; $i < count($frequency); $i++) { if (!empty($frequency[$i])) { for ($j=0; $j < $frequency[$i]; $j++) { $arr[] = $i; } } } print_r($arr);
Recommended related articles:
Usage of echo() function in php (with code)
How to configure hidden entrance in Nginx File index.php (code)
The above is the detailed content of How to implement counting sorting code in PHP. For more information, please follow other related articles on the PHP Chinese website!