原文:http://www.cnblogs.com/593213556wuyubao/archive/2012/12/17/2821890.html
原文没有对堆的大小做判断,导致取堆数据时出错!
#include "iostream"
#define MAX 0x7fffffff
using namespace std;
//heap_size小于等于20
int B[20],heap_size=0;
int counter=0;
int parent(int i){
return i/2;
}
int left(int i){
return 2*i;
}
int right(int i){
return 2*i+1;
}
void decrease_Key(int A[],int i,int key){
int temp;
A[i] = key;
while(i > 1 && A[parent(i)] < A[i]){
temp = A[i];
A[i] = A[parent(i)];
A[parent(i)] = temp;
i = parent(i);
}
}
void insert_MinHeap(int A[],int key){
heap_size++;
A[heap_size] = MAX;
decrease_Key(A,heap_size,key);
}
void minHeapify(int A[],int i){
int l,r;
l = left(i);
r = right(i);
int smallest;
if(l <= heap_size && A[i] < A[l])
smallest = l;
else
smallest = i;
if(r <= heap_size && A[smallest] < A[r])
smallest = r;
int temp;
if(smallest != i){
temp = A[i];
A[i] = A[smallest];
A[smallest] = temp;
minHeapify(A,smallest);
}
}
int extract_MinHeap(int A[]){
if(heap_size > 0)
{
int x = A[1];
cout<<heap_size<<endl;
A[1] = A[heap_size];
heap_size--;
minHeapify(A,1);
return x;
}
else
return -1;
}
void enQueue(int A[],int data){
B[counter] = data;
insert_MinHeap(A,counter);
counter++;
}
int deQueue(int A[]){
int i = extract_MinHeap(A);
if(i < 0)
return MAX;
return B[i];
}
int main(){
int A[20];
enQueue(A,12);
enQueue(A,45);
enQueue(A,34);
cout<<deQueue(A)<<endl;
cout<<deQueue(A)<<endl;
cout<<deQueue(A)<<endl;
if(heap_size > 0)
{
cout<<deQueue(A)<<endl;
}
return 0;
}