计数排序算法原理与步骤
计数排序的应用场景受限,仅当键值的变动范围不超过待排序元素的总数量时才适用。它常被作为基数排序等高级排序算法的子模块,以优化处理更大规模键值的能力。
作为一种稳定的线性时间复杂度排序方法,计数排序依赖一个辅助数组C。数组C中索引i处的值代表原数组A中数值等于i的元素个数。随后依据数组C的统计结果,将原数组A中的元素放置到正确的排序位置。
计数排序算法的标准实现逻辑主要包含以下流程:
第一步,遍历待排序数组,识别其中的最大值和最小值;
第二步,遍历数组统计每个数值i出现的频次,并将结果记录在辅助数组C的第i项中;
第三步,对辅助数组C进行前缀和计算,即从第一项开始,每一项加上前一项的值,形成累计计数;
第四步,反向填充目标数组。对于原数组中的每个元素i,将其放入新数组的第C[i]个位置,并在放置后使C[i]减1,以确保相同元素的相对顺序稳定。
以下是基于PHP语言实现的计数排序算法代码示例:
<?php
function counting_sort($my_array, $min, $max)
{
$count = array();
for($i = $min; $i <= $max; $i++)
{
$count[$i] = 0;
}
foreach($my_array as $number)
{
$count[$number]++;
}
$z = 0;
for($i = $min; $i <= $max; $i++) {
while( $count[$i]-- > 0 ) {
$my_array[$z++] = $i;
}
}
return $my_array;
}
$test_array = array(3, 0, 2, 5, -1, 4, 1);
echo "原始数组 :\n";
echo implode(', ',$test_array );
echo "\n排序后数组\n:";
echo implode(', ',counting_sort($test_array, -1, 5)). PHP_EOL;</code></pre>
程序运行后的输出结果如下:
原始输入数组 : 3, 0, 2, 5, -1, 4, 1
排序完成后的数组 :-1, 0, 1, 2, 3, 4, 5
接下来补充另一个具体的应用案例
1、计数排序仅适用于整数且数据分布范围较小的排序任务
<pre class="brush:php;"><code class="language-php">
<?php
$arr = [95,94,91,98,99,90,99,93,91,92];
function countSort($arr){
$max = $arr[0];
$min = $arr[0];
for($i=0;$i<count($arr);$i++){
if($arr[$i]>$max){
$max = $arr[$i];
}
if($arr[$i] < $min){
$min = $arr[$i];
}
}
try{
$frequency = new SplFixedArray($max-$min+1);
for($i=0;$i<count($arr);$i++){
if(empty($frequency[$arr[$i]-$min]))
$frequency[$arr[$i]-$min] = 0;
$frequency[$arr[$i]-$min] += 1;
}
$sum = 0;
for ($i=0; $i < count($frequency); $i++) {
$sum += $frequency[$i];
$frequency[$i] = $sum;
}
$splfixed = new SplFixedArray(count($arr));
for($i=(count($arr)-1);$i>=0;$i--){
$splfixed[$frequency[$arr[$i]-$min]-1] = $arr[$i];
$frequency[$arr[$i]-$min] -= 1;
}
}catch(RuntimeException $re){
echo "RuntimeException: ".$re->getMessage()."\n";
}
print_r($splfixed->toArray());
}
countSort($arr);
?>
执行输出
Array ( [0] => 90 [1] => 91 [2] => 91 [3] => 92 [4] => 93 [5] => 94 [6] => 95 [7] => 98 [8] => 99 [9] => 99 )
2、php计数排序
首先获取序列中的最小值min和最大值max,时间复杂度为O(n) 接着统计min到max之间所有数值在序列中出现的频率,时间复杂度为O(n) 最后按顺序输出min到max之间的所有值,若出现次数为0则跳过,否则根据次数重复输出对应值,时间复杂度为O(k),其中k表示数据范围的大小
假设输入序列为: 2, 4, 6, 9, 4, 8
此时 min = 2, max = 9, n(元素总数)为6, k(数据范围)为8
统计各数值出现的次数结果为
[2 => 1, 3 => 0, 4 => 2, 5 => 0, 6 => 1, 7 => 0, 8 => 1, 9 => 1]
最终输出的排序结果为
2, 4, 4, 6, 8, 9
由此可见,计数排序的时间复杂度为O(n) + O(k),这取决于数据量n和数据范围k。 当n与k数值接近时,可近似视为O(n)。 此外,由于需要统计频次,如果数据范围极大而数据本身非常稀疏,将会导致较大的空间资源浪费。
class CountSort
{
private $originalData = [];
private $rangeMap = [];
private $resultData = [];
public function __construct($original = [])
{
$this->originalData = $original;
}
public function sort()
{
list($min, $max) = $this->calculateDataRange();
$this->statisticNumberOfOccurrence($min, $max);
$this->resultData = $this->generateResult();
return $this->resultData;
}
protected function calculateDataRange()
{
$max = null;
$min = null;
foreach ($this->originalData as $value) {
if (!is_null($max)) {
if ($value > $max) {
$max = $value;
}
} else {
$max = $value;
}
if (!is_null($min)) {
if ($value < $min) {
$min = $value;
}
} else {
$min = $value;
}
}
return [$min, $max];
}
protected function statisticNumberOfOccurrence($min, $max)
{
for ($i = $min; $i <= $max; $i++) {
$this->rangeMap[$i] = 0;
}
foreach ($this->originalData as $value) {
$this->rangeMap[$value]++;
}
}
protected function generateResult()
{
$result = [];
foreach ($this->rangeMap as $key => $value) {
if ($value != 0) {
for ($i = 0; $i < $value; $i++) {
array_push($result, $key);
}
}
}
return $result;
}
}
$testData = [2, 3, 4, 3, 10, 30, 20, 15, 10, 12, 33];
$countSort = new CountSort($testData);
echo '';
var_dump($countSort->sort());
执行输出
array(11) {
[0]=>
int(2)
[1]=>
int(3)
[2]=>
int(3)
[3]=>
int(4)
[4]=>
int(10)
[5]=>
int(10)
[6]=>
int(12)
[7]=>
int(15)
[8]=>
int(20)
[9]=>
int(30)
[10]=>
int(33)
}
到此这篇关于php计数排序算法的实现代码的文章就介绍到这了,更多相关php计数排序内容请搜索本站以前的文章或继续浏览下面的相关文章希望大家以后多多支持本站!