2️⃣0️⃣ 堆(完全二叉树)
😁 相比上一节的红黑树,这个代码好理解多了~
#include <iostream>
using namespace std;
class MaxHeap{
private:
int* heapArray;
int maxSize;
int currentSize;
void trickleUp(int); //向上渗透
void trickleDown(int);//向下渗透
public:
MaxHeap(int mx=10);
~MaxHeap();
bool Ismpty();
void Push(const int);
void Pop();
int Top()const;
};
MaxHeap::MaxHeap(int mx){
if(mx<1)
throw"max size must be >=1.";
maxSize = mx;
currentSize = 0;
heapArray = new int [maxSize];
}
MaxHeap::~MaxHeap(){
delete []heapArray;
}
bool MaxHeap::Ismpty(){
return currentSize==0;
}
void MaxHeap::Push(const int x){
if(currentSize == maxSize)
throw"MaxHeap is full.";
heapArray[currentSize] = x;
trickleUp(currentSize++);
}
void MaxHeap::trickleUp(int index){
int parent = (index-1)/2;
int bottom = heapArray[index];
while (index > 0 && bottom > heapArray[parent]){
heapArray[index] = heapArray[parent];
index = parent;
parent = (parent-1)/2;
}
heapArray[index] = bottom;
}
int MaxHeap::Top()const{
return heapArray[0];
}
void MaxHeap::Pop(){
heapArray[0] = heapArray [--currentSize];
trickleDown(0);
}
void MaxHeap::trickleDown(int index){
int largerChild;
int top = heapArray[index];
while(index < currentSize/2)
{
int LeftChild = 2*index + 1;
int RightChild = LeftChild + 1;
if(RightChild < currentSize && heapArray[LeftChild] < heapArray[RightChild])
largerChild = RightChild;
else largerChild = LeftChild;
if(top >= heapArray[largerChild])
break;
else heapArray[index] = heapArray[largerChild];
index = largerChild;
}
heapArray[index] = top;
}
int main(){
MaxHeap h(100);
cout << h.Ismpty() << endl;
h.Push(20);
h.Push(30);
h.Push(15);
cout << h.Top() << endl;
h.Push(90);
h.Push(35);
cout << h.Top() << endl;
h.Pop();
cout << h.Top() << endl;
h.Pop();
cout << h.Top() << endl;
return 0;
}