7-堆排序(2)-PHP版

93 阅读1分钟
<?php
/**
 * Created by PhpStorm.
 * User: admin
 * Date: 2021.2.4
 * Time: 15:16
 */

class MaxHeap2 {
    public $data;
    public $count;
    public $heapLen;

    public function __construct(array $data)
    {
        $this->count = count($data);
        $this->heapLen = count($data);
        for ($i=0;$i<$this->count;$i++) {
            $this->data[$i+1] = $data[$i];
        }

        for ($i = intval($i/2);$i>=1;$i--) {
            $this->shiftDown($i);
        }
    }

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

    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 isEmpty() {
        return $this->count == 0;
    }

    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;
    }
}

include_once '../Util.php';
$int = 1000000;
$array = makeArray($int);
echo "array:".(implode(',',$array))."\r\n";

$heap = new MaxHeapOfHeapify($array);
echo "heapArray:".(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";