参考:http://blog.csdn.net/jkay_wong/article/details/6877446
上篇博客我们主要介绍了二叉排序树的设计,这篇博客我们主要讲解堆的实现!注意
堆是最大/最小完全二叉树
,因此,我们可以用相应的性质设计!
#include <iostream>
using namespace std;
class MaxHeap{
private:
int *heap;
int curSize;
int maxSize;
public:
MaxHeap(int maxSize = 15){
this->maxSize = maxSize;
curSize = 0;
heap = new int[this->maxSize + 1];
}
~MaxHeap(){
delete[] heap;
}
int size() const{
return curSize;
}
bool empty(){
if (curSize == 0){
return true;
}
else{
return false;
}
}
int maxEle() const{
if (curSize == 0)
return -1;
else
return heap[1];
}
void show(){
if (curSize != 0){
for (int i = 1; i <= curSize; i++){
cout << heap[i] << " ";
}
cout << endl;
}
}
MaxHeap& insert(int ele){
if (curSize == maxSize){
return *this;
}
int i = ++curSize;
//由叶子节点向父节点传递
while (i != 1 && ele > heap[i / 2]){
heap[i] = heap[i / 2];
i = i / 2;
}
heap[i] = ele;
cout << "插入成功!" << endl;
return *this;
}
MaxHeap& delMax(int& ele){
if (curSize == 0){
return *this;
}
ele = heap[1];
heap[1] = heap[curSize--];
int temp = heap[1];
//从上往下传递
int pos = 1;
int child = 2 * pos + 1;
while (child <= curSize){
if (child + 1 <= curSize&&heap[child] < heap[child + 1]){
child++;
}
if (temp < heap[child]){
heap[child / 2] = heap[child];
pos = child;
child = 2 * pos + 1;
}
else{
break;
}
}
heap[pos] = temp;
/*
int i = 1;
int pos = 2;
while (pos <= curSize){
if (pos<curSize&&heap[pos]<heap[pos + 1]){
pos++;
}
if (temp > heap[pos]){
break;
}
heap[pos / 2] = heap[pos];
pos = pos * 2;
}
heap[pos / 2] = temp;
*/
return *this;
}
void Init_heap(int a[], int size, int maxSize){
delete[] heap;
heap = new int[maxSize + 1];
curSize = size;
this->maxSize = maxSize;
for (int j = 1; j < size + 1; j++){
heap[j] = a[j];
}
for (int i = curSize / 2; i >= 1; i--){
int curNode = heap[i];
int child = 2 * i;
while (child <= curSize){
if (child < curSize&&heap[child] < heap[child + 1]){
child++;
}
if (curNode > heap[child]){
break;
}
heap[child / 2] = heap[child];
child *= 2;
}
heap[child / 2] = curNode;
}
}
};
int main(){
MaxHeap maxHeap;
int a[12] = { -123, 34, 45, 1, 34, 12, 32, 45, 2, 1, 234, 43 };
maxHeap.Init_heap(a, 11, 15);
maxHeap.show();
maxHeap.insert(20);
maxHeap.insert(1000);
maxHeap.insert(20000);
maxHeap.show();
//删除节点输出
int max = 0;
maxHeap.delMax(max);
maxHeap.show();
return 0;
}
运行结果:
PS:需要注意的是如果节点的左右两个节点的值相同,此时,堆排序可能失效!!!