第六章堆排序之“刪除最大堆中的指定元素HEAP-DELETE”(練習6.5-7)

來源:互聯網
上載者:User

題目:HEAP-DELETE(A,i)操作將節點i中的項從堆中刪去。對含n個元素的最大堆,請給出時間為O(lgn)的HEAP-DELETE的實現。

編程思路:

我們可以用堆中最後一個元素a[heapSize]放到節點i 位置,然後將heapSize減一。然後就涉及到堆調整以保持堆的性質。

調整的依據就是這最後一個元素a[heapSize]跟原來i節點的元素a[i]的相對大小,分三種情況:

(1)當a[heapSize]==a[i]時,最大堆不用調整。時間複雜度為O(1)

(2)當a[heapSize]<a[i]時,以i節點為根的子分支堆性質遭到破壞,其他地方不變,所以這裡直接調用保持堆性質的函數MaxHeapIfy()進行堆調整即可。時間複雜度為O(lgn)

(3)當a[heapSize]>a[i]時,這種情況類似於“將優先隊列的某個元素關鍵字值增大到k”的操作,所以直接調用HeapIncreaseKey()函數即可。時間複雜度為O(lgn)

實現代碼如下:

//堆調整,保持堆的性質 void MaxHeapIfy(int *a,int i,int heapSize){int largest=0;int left=0;int right=0;int tmp=0;if(left<=heapSize&&a[i]<a[left]){largest=left;}else{largest=i;}if(right<=heapSize&&a[largest]<a[right]){largest=right;}if(i!=largest){tmp=a[i];a[i]=a[largest];a[largest]=tmp;MaxHeapIfy(a,largest,heapSize);}}//將堆中元素x的關鍵字值增大到k,k要大於x原關鍵字的值void HeapIncreaseKey(int *a,int x,int k){int tmp=0;if(k<a[x]){return;}while(x>1&&a[x>>1]<a[x]){tmp=a[x];a[x]=a[x>>1];a[x>>1]=tmp;x>>=1;}}//刪除堆中指定元素ivoid HeapDelete(int *a,int i,int *heapSize){int tmp=a[*heapSize];if(a[i]==tmp){(*heapSize)--;}else if(a[i]>tmp)//i節點換成較小的tmp後,所在分支的最大堆性質可能遭到破壞,要進行調整 {a[i]=tmp;(*heapSize)--;MaxHeapIfy(a,i,*heapSize);}else if(a[i]>tmp)//i節點的值增大到更大的tmp {(*heapSize)--;HeapIncreaseKey(a,i,tmp);}} int main(){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.