满二叉树中如果子节点的位置是n(位置从0开始),那么他的父节点的位置是(n-1)/2
MaxHeap.h
#pragma once
#include <iostream>
//using namespace std;
template<class T>
class MaxHeap
{
public:
MaxHeap(int mx=10);
~MaxHeap();
bool IsEmpty();
void Push(const T&);
void Pop();
const T& Top() const;
private:
T* heapArray;
int maxSize;
int curSize;
void trickleUp(int index); //向上冒泡
void trickleDown(int index); //向下冒泡
};
template<class T>
MaxHeap<T>::MaxHeap(int mx)
{
if(mx < 1)
throw "max size must be > 1";
this->maxSize = mx;
this->curSize = 0;
this->heapArray = new T[maxSize];
}
template<class T>
bool MaxHeap<T>::IsEmpty()
{
return (curSize == 0);
}
template<class T>
void MaxHeap<T>::Push(const T& data)
{
if(curSize == maxSize)
throw "MaxHeap is full";
heapArray[curSize] = data;
trickleUp(curSize); //向上冒泡,找到合适的位置
curSize++;
}
template<class T>
void MaxHeap<T>::Pop()
{
heapArray[0] = heapArray[--curSize]; //一定要--,因为是下标
trickleDown(0); //从根开始向下渗透
}
template<class T>
MaxHeap<T>::~MaxHeap()
{
delete[] heapArray;
}
template<class T>
void MaxHeap<T>::trickleUp(int index) //向上冒泡
{
int parent = (index - 1)/2;
T temp = heapArray[index];
while(index > 0 && heapArray[parent] < temp)
{
heapArray[index] = heapArray[parent];
index = parent;
parent = (parent - 1) / 2; //不断向上
}
heapArray[index] = temp; //插入位置
}
template<class T>
void MaxHeap<T>::trickleDown(int index) //向下冒泡
{
T top = heapArray[index]; //保存临时的根
int leftChild = 0;
int rightChild = 0;
int largerChild = 0;
while(index < curSize/2) //到最后一层的上一层,就可以操作他的子节点
{
leftChild = 2 * index + 1;
rightChild = leftChild + 1; //从0开始的下标
//rightChild < curSize 是判断最后一个父节点有左右两个节点,还是只有一个左节点
if(rightChild < curSize && heapArray[leftChild] < heapArray[rightChild])
largerChild = rightChild;
else //只有一个左节点或者左节点的数大
largerChild = leftChild;
if(top >= heapArray[largerChild]) //找到位置
break;
else
{
heapArray[index] = heapArray[largerChild];
index = largerChild; //继续向下渗透
}
}
heapArray[index] = top;
}
template<class T>
const T& MaxHeap<T>::Top() const
{
return heapArray[0];
}
main.h
#include <iostream>
#include "MaxHeap.h"
using namespace std;
int main()
{
MaxHeap<int> heap(100);
cout << heap.IsEmpty() << endl;
heap.Push(20);
heap.Push(30);
heap.Push(15);
cout << "最大值是: " << heap.Top() << endl;
heap.Push(90);
cout << "最大值是: " << heap.Top() << endl;
heap.Pop();
cout << "最大值是: " << heap.Top() << endl;
return 0;
}