PHP数据结构:堆数据结构的奥妙,实现高效的排序与优先级队列

wufei1232024-05-14PHP48
php 中的堆数据结构是一种满足完全二叉树和堆性质(父结点值大于/小于子结点值)的树状结构,使用数组实现。堆支持两种操作:排序(从小到大提取最大元素)和优先级队列(根据优先级提取最大元素),分别通过 heapifyup 和 heapifydown 方法维护堆的性质。PHP数据结构:堆数据结构的奥妙,实现高效的排序与优先级队列PHP 中的堆数据结构:揭秘排序和优先级队列的奥秘堆是一种树状数据结构,它满足以下两个性质:完全二叉树性质:树中的每个结点都有两个子结点,或者没有子结点,形成一棵完全二叉树。堆性质:每个父结点的值都大于(或等于)它的两个子结点的值(最大堆)或小于(或等于)它的两个子结点的值(最小堆)。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) / 2); 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 = 2 * $index + 1; $rightIndex = 2 * $index + 2; 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); } }}

发表评论

访客

◎欢迎参与讨论,请在这里发表您的看法和观点。