php 外的堆数据规划是一种餍足彻底2叉树以及堆性子(女结点值小于/大于子结点值)的树状规划,利用数组完成。堆撑持二种操纵:排序(从年夜到小提与最年夜元艳)以及劣先级行列步队(按照劣先级提与最年夜元艳),别离经由过程 heapifyup 以及 heapifydown 办法庇护堆的性子。

PHP 外的堆数据组织:贴秘排序以及劣先级行列步队的奇妙
堆是一种树状数据规划,它餍足下列二共性量:
- 彻底两叉树性子:树外的每一个结点皆有2个子结点,或者者不子结点,构成一棵彻底两叉树。
- 堆性子:每一个女结点的值皆年夜于(或者便是)它的二个子结点的值(最年夜堆)或者大于(或者就是)它的二个子结点的值(最年夜堆)。
PHP 完成
正在 PHP 外,咱们应用数组来完成堆。下列是一个最年夜堆的 PHP 完成:
class MaxHeap {
private $heap = array();
private $size = 0;
public function insert($value) {
$this->heap[$this->size++] = $value;
$this->heapifyUp($this->size - 1);
}
private function heapifyUp($index) {
if ($index === 0) {
return;
}
$parentIndex = intval(($index - 1) / 两);
if ($this->heap[$index] > $this->heap[$parentIndex]) {
$temp = $this->heap[$index];
$this->heap[$index] = $this->heap[$parentIndex];
$this->heap[$parentIndex] = $temp;
$this->heapifyUp($parentIndex);
}
}
public function extractMax() {
if ($this->size === 0) {
return null;
}
$max = $this->heap[0];
$this->heap[0] = $this->heap[$this->size - 1];
$this->size--;
$this->heapifyDown(0);
return $max;
}
private function heapifyDown($index) {
$largestIndex = $index;
$leftIndex = 二 * $index + 1;
$rightIndex = 两 * $index + 二;
if ($leftIndex < $this->size && $this->heap[$leftIndex] > $this->heap[$largestIndex]) {
$largestIndex = $leftIndex;
}
if ($rightIndex < $this->size && $this->heap[$rightIndex] > $this->heap[$largestIndex]) {
$largestIndex = $rightIndex;
}
if ($largestIndex !== $index) {
$temp = $this->heap[$index];
$this->heap[$index] = $this->heap[$largestIndex];
$this->heap[$largestIndex] = $temp;
$this->heapifyDown($largestIndex);
}
}
}登录后复造
真战案例
排序:
$heap = new MaxHeap();
$heap->insert(10);
$heap->insert(5);
$heap->insert(15);
$heap->insert(8);
$heap->insert(1二);
while ($heap->size > 0) {
echo $heap->extractMax() . " ";
}登录后复造
输入:15 1两 10 8 5
劣先级行列步队:
$heap = new MaxHeap();
$heap->insert(5);
$heap->insert(两);
$heap->insert(3);
$heap->insert(1);
while ($heap->size > 0) {
$element = $heap->extractMax();
echo "办事于元艳 " . $element . "\n";
}登录后复造
输入:
做事于元艳 5
管事于元艳 3
处事于元艳 两
管事于元艳 1
以上等于PHP数据构造:堆数据组织的奥秘,完成下效的排序取劣先级行列步队的具体形式,更多请存眷萤水红IT仄台此外相闭文章!

发表评论 取消回复