第六章堆排序之“最小優先順序隊列”(練習6.5-3)

來源:互聯網
上載者:User

用最小堆實現最小優先順序隊列:

//返回堆中關鍵字最小的元素

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; }

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.