代码:
#include "iostream" #define MAX 0x7fffffff using namespace std; 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[]){ int x=A[1]; A[1]=A[heap_size]; heap_size--; minHeapify(A,1); return x; } void enQueue(int A[],int data){ counter++; B[counter]=data; insert_MinHeap(A,counter); } int deQueue(int A[]){ int i=extract_MinHeap(A); return B[i]; } int m=0; int add(){ m++; return m; } void 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; getchar(); getchar(); }