How to implement counting sorting code in PHP

不言
Release: 2023-04-03 14:14:01
Original
1554 people have browsed it

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);
Copy after login

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!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template