用最小堆實現最小優先順序隊列:
//返回堆中關鍵字最小的元素
HeapMinimum()
//去掉並返回堆中關鍵字最小的元素
HeapExtractMin()
//將堆中元素x的關鍵字減小到k,k要小於x原來的關鍵字值
HeapDecreaseKey()
//將元素x插入到堆中
MInHeapInsert()
#include <stdio.h>#include <string.h>#include <time.h>#define BUFFER_SIZE 10//堆調整,保持堆的性質 void MinHeapIfy(int *a,int i,int heapSize){int left=0;int right=0;int smallest=i;int tmp=0;while(i<heapSize){left=i<<1;right=(i<<1)+1;smallest=i;if(left<=heapSize&&a[i]>a[left]){smallest=left;}if(right<=heapSize&&a[smallest]>a[right]){smallest=right;}if(smallest!=i){tmp=a[i];a[i]=a[smallest];a[smallest]=tmp;i=smallest;}else{break;}}}//建堆void BuildMinHeap(int *a,int heapSize){int i=0;for(i=heapSize/2;i>0;i--){MinHeapIfy(a,i,heapSize);}} //返回堆中具有最小關鍵字的元素 int HeapMinimum(int *a){return a[1];} //去掉並返回堆中具有最小關鍵字的元素int HeapExtractMin(int *a,int *heapSize){int min=a[1];a[1]=a[*heapSize];(*heapSize)--;MinHeapIfy(a,1,*heapSize);return min;} //將堆中元素x的關鍵字值減小到k,k要小於x原關鍵字的值void HeapDecreaseKey(int *a,int x,int k){int tmp=0;if(k>=a[x]){return;}a[x]=k;while(x>1&&a[x]<a[x>>1]){tmp=a[x];a[x]=a[x>>1];a[x>>1]=tmp;x>>=1;} }//把元素x插入堆中void MinHeapInsert(int *a,int x,int *heapSize){a[*heapSize+1]=x+1;//賦予新添加的值不能小於x,因為還要調用HeapDecreaseKey()將它的值減小到xHeapDecreaseKey(a,*heapSize+1,x); (*heapSize)++;}//輸出堆中的元素 void Output(int *a,int len){int i=0;for(i=1;i<len+1;i++){printf("%d ",a[i]);}printf("\n");}int main(){int i=0;int heapSize=BUFFER_SIZE;int a[BUFFER_SIZE+1];memset(a,0,sizeof(a));srand((unsigned)time(NULL));for(i=1;i<BUFFER_SIZE+1;i++){a[i]=rand()%BUFFER_SIZE+1;}printf("隨機產生的數組:"); Output(a,BUFFER_SIZE);//建堆 BuildMinHeap(a,heapSize);printf("建立的堆為:");Output(a,heapSize);//返回堆中關鍵字最小的元素 printf("堆中關鍵字最小的元素:%d\n",HeapMinimum(a));//去掉並返回堆中關鍵字最小的元素HeapExtractMin(a,&heapSize);printf("去掉並返回堆中關鍵字最小的元素:");Output(a,heapSize);//將堆中第四個元素的值減小到-1 HeapDecreaseKey(a,4,-1);printf("將堆中第四個元素的值減小到-1後,堆為:");Output(a,heapSize);//將-5插入到堆中MinHeapInsert(a,-5,&heapSize);printf("將-5插入到堆中後,堆為:");Output(a,heapSize);system("pause");return 0; }