堆排序(Heapsort),顾名思义就是借助(Deap)这个数据结构来排序。堆的实现有很多种,但它们都支持常见的几种操作。
1、建堆(即初始化堆)
2、查找最大值或最小值,一般只支持其中的一种。用于查找最大值的堆叫作最大堆,用于查找最小值的堆叫做最小堆。
3、删除最大值或删除最小值
4、插入(即插入一个新的元素到堆)
这里我们只考虑最小堆。堆的最简单的一个实现就是二叉堆。假设堆中有n个对象,则二叉堆的几个操作复杂度分别如下。
建堆:O(N)。
查找最小值:O(1)。
删除最小值:O(logn)。
插入:O(logn)。
堆排序的流程非常简单,就是直接利用堆的这几种操作。我们只需对全部待排序对象建堆,然后反复查找并删除最大值即可。这样我们就可以得到一个从大到小排序后的结果。<?php
/**
* 堆排序
* @author i@zhanglirong http://www.zhanglirong.cn
* @date 2017.08.15
* @time 06:30 pm
*/
$arr = array(4,2,6,1,8,10,13,5,26,7);
$count = count($arr);
//排序
heapSort($arr, $count);
for ($i = $count - 1; $i > 0; $i--){
swap($arr, $i, 0);
$count--;
heapSort($arr, $count);
}
print_R($arr);die;
//用数组建立最小堆
function heapSort(&$arr, $count){
for ($index = intval($count / 2) - 1; $index >= 0; $index--){
//如果有左节点,讲其下标存进最小量$min
if($index*2+1
$min=$index*2+1;
if($index*2+2
if($arr[$index*2+2]
$min=$index*2+2;
}
}
//将子节点中较小的和父节点比较,若子节点较小,与父节点交换位置,同时更新较小
if($arr[$min]
swap($arr, $min, $index);
}
}
}
}
//交换
function swap(&$arr, $one, $another){
$temp = $arr[$one];
$arr[$one] = $arr[$another];
$arr[$another] = $temp;
}
输出的结果:wutongdeMacBook-Pro:sort wutong$ php heapsort.php
Array
(
[0] => 26
[1] => 13
[2] => 10
[3] => 8
[4] => 7
[5] => 6
[6] => 5
[7] => 4
[8] => 2
[9] => 1
)