堆排序,堆排序演算法

來源:互聯網
上載者:User

堆排序,堆排序演算法

在利用最小堆進行排序時,需要執行N次deleteMin操作。按照順序,最小的元素先離開堆。通過將這些元素記錄到第二個數組然後再將數組拷貝回來,我們得到N個元素的排序。由於每個deleteMin花費O(logN)時間,因此總的已耗用時間是O(NlogN)。
該演算法的主要問題在於,它使用了一個附加的數組。因此,儲存需求增加一倍。在某些執行個體中這可能是個問題。注意,將第二個數組複製回第一個數組的附加時間消耗只是O(N),這不可能顯著影響已耗用時間,。這個問題是空間的問題。
避免使用第二個數組的聰明的方法是利用這樣的事實:在每次deleteMin之後,堆縮小了1。因此,堆中最後的單元可以用來存放剛剛刪去的元素。例如,設我們有一個堆,它含有6個元素。第一次deleteMin產生a1。現在該堆只有5個元素,因此可以吧a1放在位置6上。下一次deleteMin產生a2,由於該堆現在只有4個元素,因此把a2放在位置5上。
使用這種策略,在最後一次deleteMin後,該數組將以遞減順序包含這些元素。如果想將這些元素排成更典型的遞增順序,那麼可以改變堆序性質使得父親的元素的值大於兒子的值。這樣就得到max堆。
下面這段代碼使用一個max堆。不像二元堆積,二元堆積的資料是從數組下標1處開始,而此處堆排序的數組包含位置0處的資料。

/*** Standard heapsort.* /tempalte <typename Comparable>void heapsort(vector<Comparable> & a){   for(int i=a.size()/2;i>=0;i--) /* buildHeap */       percDown(a,i,a,size());   for(int j=a.size()-1;j>0;j--)   {          swap( a[0],a[j]);  /*deleteMax*/       percDown(a,0,j);   }}/*** Internal method for heapsort.*  i is the index of an item in the heap.*  Returns the index of the left child.* /inline int leftChild( int i){      return 2*i+1;}/*** Internal method for heapsort that is used in deleteMax and buildHeap.* i is the position fron which to percolate down.* n is the logical size of the binary heao.* /template< typename Comparable>void percDown(vector<Comparable> & a, int i,int n){   int child;   Comparable tmp;   for(tmp=a[i];leftChild(i)<n;i=child)   {         child=leftChild(i);       if(child!=n-1 && a[child] <a[child+1] )           child++;       if(tmp<a[child])          a[i]=a[child];       else          break;   }   a[i]=tmp;}

著作權聲明:本文為博主原創文章,未經博主允許不得轉載。

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.