大根堆算法代码实现
时间: 2023-08-20 19:17:21 浏览: 140
下面是大根堆的算法代码实现,包括插入元素、删除堆顶元素和向下调整操作:
```
class MaxHeap:
def __init__(self):
self.heap = []
def insert(self, val):
self.heap.append(val)
self._sift_up(len(self.heap) - 1)
def pop_max(self):
if len(self.heap) == 0:
return None
elif len(self.heap) == 1:
return self.heap.pop()
else:
max_val = self.heap[0]
self.heap[0] = self.heap.pop()
self._sift_down(0)
return max_val
def _sift_up(self, index):
parent = (index - 1) // 2
if index > 0 and self.heap[index] > self.heap[parent]:
self.heap[index], self.heap[parent] = self.heap[parent], self.heap[index]
self._sift_up(parent)
def _sift_down(self, index):
left = 2 * index + 1
right = 2 * index + 2
largest = index
if left < len(self.heap) and self.heap[left] > self.heap[largest]:
largest = left
if right < len(self.heap) and self.heap[right] > self.heap[largest]:
largest = right
if largest != index:
self.heap[index], self.heap[largest] = self.heap[largest], self.heap[index]
self._sift_down(largest)
```
其中,`insert` 方法用于插入元素,向上调整以满足大根堆的性质;`pop_max` 方法用于删除堆顶元素,将最后一个元素放到堆顶,然后向下调整以满足大根堆的性质;`_sift_up` 方法用于向上调整,`_sift_down` 方法用于向下调整。
阅读全文