* autoload.php
接上次的blog => https://blog.csdn.net/fareast_mzh/article/details/82832668
<?php
$prefixList = ['stack\\dogcat', 'stack', 'Heap'];
array_walk($prefixList, function($prefix) {
spl_autoload_register(function($class) use ($prefix) {
$base_dir = __DIR__ . DIRECTORY_SEPARATOR. str_replace('\\', '/', $prefix);
$len = strlen($prefix);
if (strncmp($prefix, $class, $len) !== 0) {
return;
}
$relative_class = substr($class, $len);
$file = $base_dir . str_replace('\\', '/', $relative_class) . '.php';
if (!file_exists($file)) {
throw new InvalidArgumentException($file.' does not exist');
}
require $file;
});
}, null);
* 目录结构
* Heap/BinHeap.php [ONGOING]
<?php
/**
* 完全二叉树的数组实现
* ==============================
* A
* / \
* B C
* / \ / \
* D E F G
* /\ /
* H I J
* ===============================
* _ A B C D E F G H I J _ _ _
* 0 1 2 3 4 5 6 7 8 9 10 11 12 13
*/
namespace Heap;
class BinHeap {
/** @var int */
protected $capacity;
/** @var int */
protected $size;
/** @var \SplFixedArray */
protected $elements;
const MIN_PQSIZE = 4;
const MIN_DATA = null;
public function __construct(int $maxElements) {
if ($maxElements < self::MIN_PQSIZE) {
throw new \AssertionError("Priority queue size is too small");
}
$this->elements = new \SplFixedArray($maxElements + 1);
$this->capacity = $maxElements;
$this->size = 0;
/* dumb position 0 */
$this->elements[0] = self::MIN_DATA;
}
public function isFull() {
return $this->size >= $this->capacity;
}
public function insert($x) {
if ($this->isFull()) {
throw new \RuntimeException("Priority queue is full");
}
for ($i = ++$this->size; $this->elements[$i>>1] > $x; $i >>= 1) {
$this->elements[$i] = $this->elements[ $i>>1 ];
}
$this->elements[ $i ] = $x;
}
public function isEmpty() {
return $this->size === 0;
}
public function deleteMin() {
if ($this->isEmpty()) {
// throw new \RuntimeException("Priority queue is empty");
return $this->elements[0];
}
$minElement = $this->elements[1];
$lastElement = $this->elements[$this->size--];
for ($i = 1; $i * 2 <= $this->size; $i = $child) {
/* find smaller child */
$child = $i * 2;
if ($child !== $this->size && $this->elements[$child+1]
< $this->elements[$child]) {
$child++;
}
/* Percolate one level */
if ($lastElement > $this->elements[$child]) {
$this->elements[$i] = $this->elements[$child];
} else {
break;
}
}
$this->elements[$i] = $lastElement;
return $minElement;
}
}
* index2.php
<?php
include './autoload.php';
use Heap\BinHeap;
$heap = new BinHeap(14);
var_dump($heap);