【天天数据结构和算法】最大堆实现排序

<?php

class MaxHeap
{
    private $data;
    private $count;
    private $capacity;

    public function __construct(int $capcity)
    {
        $this->data = new SplFixedArray($capcity);
        $this->count = 0;
        $this->capacity = $capcity;
    }

    public function __destruct()
    {
        // TODO: Implement __destruct() method.
        unset($this->data);
    }

    public function size()
    {
        return $this->count;
    }

    public function isEmpty()
    {
        return $this->count == 0;
    }

    public function insert(int $item)
    {
        $this->data[$this->count + 1] = $item;
        $this->count++;
        $this->shiftUp($this->count);
    }
    public function insertH(int $item){
        $this->data[$this->count + 1] = $item;
        $this->count++;
        $this->shiftUpH($this->count);
    }
    private function shiftUp(int $k)
    {
        $item = $this->data[$k];
        while ($k > 1 && $this->data[$k / 2] < $item) {
            //交换优化
            //list($this->data[$k], $this->data[$k / 2]) = array($this->data[$k / 2], $this->data[$k]);
            $this->data[$k] = $this->data[$k/2];
            $k = intval($k / 2);
        }
        $this->data[$k] = $item;
    }
    private function shiftUpH(int $k)
    {
        //$item = $this->data[$k];
        while ($k > 1 && $this->data[$k / 2] < $this->data[$k]) {
            //交换优化
            list($this->data[$k], $this->data[$k / 2]) = array($this->data[$k / 2], $this->data[$k]);
            $this->data[$k] = $this->data[$k/2];
            $k = intval($k / 2);
        }
        //$this->data[$k] = $item;
    }
    private function shiftDown(int $k)
    {
        while (2 * $k <= $this->count) {
            $j = 2 * $k;
            if ($j + 1 <= $this->count && $this->data[$j + 1] > $this->data[$j])
                $j += 1;
            if ($this->data[$k] > $this->data[$j])
                break;
            list($this->data[$k],$this->data[$j]) = array($this->data[$j],$this->data[$k]);
            $k = $j;
        }
    }

    public function extractMax()
    {
        if ($this->count <= 0)
            return;
        $ret = $this->data[1];
        $this->data[1] = $this->data[$this->count];
        unset($this->data[$this->count]);
        $this->count--;
        $this->shiftDown(1);

        return $ret;
    }

    public function foreachHeap()
    {
        var_dump($this->data);
    }
}

$maxHeap = new MaxHeap(100);
for ($i = 0; $i < 31; $i++)
    $arr[] = rand(0, 99);
foreach ($arr as $v)
    $maxHeap->insert($v);
$start_time = microtime();
rsort($arr);
$end_time = microtime();
echo $end_time-$start_time;
var_dump($arr);
$start_time = microtime();
while (!$maxHeap->isEmpty()){
     $maxHeap->extractMax();
}
$end_time = microtime();
echo $end_time-$start_time;
$maxHeap->foreachHeap();

 

posted @ 2017-06-03 16:41  jysdhr  阅读(235)  评论(0编辑  收藏  举报