6-堆排序(1)-PHP版

96 阅读1分钟
<?php
/**
 * Created by PhpStorm.
 * User: admin
 * Date: 2021.2.4
 * Time: 10:17
 */

/**
 * 最大堆::父节点的值,大于左右两个节点的值
 *
 * Class MaxHeap
 */
class MaxHeap {
    public $data;
    public $count;
    public $heapLen;
    public function __construct($heapLen)
    {
        $this->data = array();
        $this->count = 0;
        $this->heapLen = $heapLen;
    }

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

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

    public function insert($value) {
        $this->data[$this->count+1] = $value;
        $this->count++;
        if($this->count > $this->heapLen) {
            echo "Heap is Full...";die;
        }
        $this->shiftUp($this->count);
    }

    private function shiftUp($count) {
        while (($count > 1) && ($this->data[intval($count / 2)] < $this->data[$count])) {
            $this->swap($this->data[intval($count / 2)],$this->data[$count]);
            $count = intval($count / 2);
        }
    }

    public function extractMax() {

        if($this->isEmpty()) {
            return -1;
        }

        if($this->count == 1) {
            $ret = $this->data[$this->count];
            unset($this->data[$this->count]);
            $this->count--;
            return $ret;
        }

        $ret = $this->data[1];
        $this->swap($this->data[1],$this->data[$this->count]);
        unset($this->data[$this->count]);
        $this->count--;
        $this->shiftDown(1);
        return $ret;
    }

    public function shiftDown($k) {
        while ($this->count >= 2*$k) {
            $left = $k * 2;
            if($left + 1 <= $this->count && $this->data[$left+1] > $this->data[$left])
                ++$left;

            if($this->data[$k] >= $this->data[$left])
                break;
            $this->swap($this->data[$k],$this->data[$left]);
            $k = $left;
        }
    }


    public function swap(&$a,&$b) {
        $temp = $a;
        $a = $b;
        $b = $temp;
    }

}

$int = 100;
$heap = new MaxHeap($int);
for ($i = 0;$i<$int;$i++) {
    $heap->insert(mt_rand(1,100));
}
echo "array:".(implode(',',$heap->data))."堆的个数:{$heap->count}"."\r\n";
$sortArr = [];
for ($i=$int-1;$i>=0;$i--) {
    $sortArr[$i] = $heap->extractMax();
}
echo "newArray:".(implode(',', $sortArr))."\r\n";