php 排序算法 堆排序

abstract class HeapSort{
protected $count;
protected $data;
public function __construct(array $data)
{
$this->count = count($data);
$this->data = $data;
}
public function run()
{
$this->createHeap();
while ($this->count > 0) {
$this->swap($this->data[0], $this->data[--$this->count]);
$this->buildHeap($this->data, 0, $this->count);
}
return $this->data;
}
public function createHeap()
{
$i = floor($this->count / 2) + 1;
while ($i--) {
$this->buildHeap($this->data, $i, $this->count);
}
}
public function swap(&$left, &$right)
{
list($left, $right) = array ($right, $left);
}

abstract public function buildHeap(array &$data, $i, $count);
}

class HeapMaxSort extends HeapSort
{
public function buildHeap(array &$data, $i, $count)
{
if (false === $i < $count) {
return;
}
$right = ($left = 2 * $i + 1) + 1;
$max = $i;
if ($left < $count && $data[$i] < $data[$left]) {
$max = $left;
}
if ($right < $count && $data[$max] < $data[$right]) {
$max = $right;
}
if ($max !== $i && $max < $count) {
$this->swap($data[$i], $data[$max]);
$this->buildHeap($data, $max, $count);
}
}
}
class HeapMinSort extends HeapSort{
public function buildHeap(array &$data,$i,$count){

if (false === $i < $count) {
return;
}

$right = ($left = 2 * $i + 1) + 1;
$min = $i;

if($left < $count && $data[$i] > $data[$left]){
$min = $left;
}

if($right < $count && $data[$min] > $data[$right]){
$min = $right;
};
if($min < $count && $min != $i){
$this->swap($data[$i], $data[$min]);
$this->buildHeap($data, $min, $count);
}
}
}
$array = array (4, 21, 41, 2, 53, 1, 213, 31, 21, 423, 56);
$result = (new HeapMinSort($array))->run();
$result1 = (new HeapMaxSort($array))->run();
print_r($result);
print_r($result1);

引用自 https://github.com/PuShaoWei/arithmetic-php,在这个基础上重构了一个从大到小的排序

转载于:https://www.cnblogs.com/hubudong/p/9811202.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值