完全二叉树叫做堆
完全二叉树就是在最后一个节点之前不允许有不满的节点(有空洞)
用数组来做完全二叉树(堆)
大顶堆,根上的数字最大(大的在上面)
小顶堆,根上的数字最小(小的在上面)
操作:
插入新节点—>向上渗透
删除根节点—>向下渗透
插入新节点,先按顺序插入到节点上,然后和父辈交换
删除根节点,先把根节点删除,然后把最后一个节点加到根上,然后和子代交换
堆用来做优先队列,用来排序(堆排序)
今天用堆做一个小例子
在头文件中加入MaxHeap.h在源文件中加入main.cpp
下面是堆的主要程序代码
//MaxHeap.h
#ifndef _MAX_HEAP_
#define _MAX_HEAP_
template<class T>
class MaxHeap{
public:
MaxHeap(int mx = 10);
virtual ~MaxHeap();
bool IsEmpty();
void Push(const T&);
void Pop();
const T& Top() const;
private:
T* heapArray;
int maxSize;
int currentSize;
void trickleUp(int index);
void trickleDown(int index);
};
template<class T>
MaxHeap<T>::MaxHeap(int mx = 10){
if (mx < 1) throw "max size must be >= 1";
maxSize = mx;
currentSize = 0;
heapArray = new T[maxSize];
}
template<class T>
MaxHeap<T>::~MaxHeap(){
delete[]heapArray;
}
template<class T>
bool MaxHeap<T>::IsEmpty(){
return currentSize == 0;
}
template <class T>
void MaxHeap<T>::Push(const T&e){
if (currentSize == maxSize) throw "MaxHeap id full.";
heapArray[currentSize] = e;
trickleUp(currentSize);
currentSize++;
}
template<class T>
void MaxHeap<T>::trickleUp(int index){
int parent = (index - 1) / 2;
T bottom = heapArray[index];
while (index>0 && heapArray[parent] < bottom){
heapArray[index] = heapArray[parent];
index = parent;
parent = (parent - 1) / 2;
}
heapArray[index] = bottom;
}
template<class T>
const T& MaxHeap<T>::Top()const{
return heapArray[0];
}
template<class T>
void MaxHeap<T>::Pop(){
heapArray[0] = heapArray[--currentSize];
trickleDown(0);
}
template<class T>
void MaxHeap<T>::trickleDown(int index){
int largerChild;
T 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;
heapArray[index] = heapArray[largerChild];
index = largerChild;
}
heapArray[index] = top;
}
#endif
下面是测试堆的代码(主函数)
//main.cpp
#include<iostream>
#include"MaxHeap.h"
using namespace std;
int main(){
MaxHeap<int> h(100);
cout << h.IsEmpty() << endl;
cout << "测试堆" << endl;
h.Push(20);
h.Push(30);
h.Push(15);
cout << h.Top() << endl;
h.Push(90);
h.Push(80);
h.Push(70);
cout << h.Top() << endl;
h.Pop();
cout << h.Top() << endl;
h.Pop();
cout << h.Top() << endl;
h.Pop();
cout << h.Top() << endl;
h.Pop();
cout << h.Top() << endl;
system("pause");
return 0;
}
总结:堆是比较常用的数据结构,可以使用数组实现堆。