C++实现小根堆
首先,我们需要了解什么是堆(heap)。堆是一种数据结构,它可以在O(log n)的时间复杂度内完成插入、删除最大/最小值的操作。堆又可以分为大根堆和小根堆两种类型,大根堆是指堆顶元素最大,而小根堆是指堆顶元素最小。
在C++中,我们可以用STL中的priority_queue来实现堆。但是如果我们想要更深入地理解堆以及手动实现堆的话,就需要自己动手写一个小根堆了。
下面是一个基于数组实现的小根堆的C++代码:
#include <iostream>
#include <vector>
using namespace std;
class MinHeap{
private:
vector<int> heap;
void percolateUp(int index){
while(index > 0){
int parentIndex = (index - 1) / 2;
if(heap[parentIndex] > heap[index]){
swap(heap[parentIndex], heap[index]);
index = parentIndex;
}
else{
break;
}