【演算法導論】堆排序C++實現(根據演算法導論而來)

來源:互聯網
上載者:User

之前看其他演算法和資料結構書的時候覺得堆排序的代碼比較難寫,今天看過《演算法導論》發現也不是那麼難,所以就動手自己寫了一個。原理就是根據演算法導論第三版堆排序虛擬碼而來的。

#include<iostream>using namespace std;const int ARRAY_SIZE=10;int a[ARRAY_SIZE]={4,1,3,2,16,9,10,14,8,7};//調整pos位置,使得pos和其直接左右孩子滿足大堆條件void max_heapify(int a[],int pos,int heap_size){int l=2*pos+1,r=2*pos+2;//因為下標從0開始,所以這裡l和r都多加了1int largest;if(l<=heap_size&&a[l]>a[pos])largest=l;elselargest=pos;if(r<=heap_size&&a[r]>a[largest])largest=r;if(largest!=pos){int tmp=a[pos];a[pos]=a[largest];a[largest]=tmp;max_heapify(a,largest,heap_size);//改變了largest位置的值,則以largest為根的子樹也要調整}}//建堆過程void build_max_heap(int a[],int n){for(int i=n/2-1;i>=0;i--)//注意數組下標從0開始,所以這裡n/2-1{max_heapify(a,i,n-1);//heap_size=n-1}}int main(){build_max_heap(a,ARRAY_SIZE);for(int i=ARRAY_SIZE-1;i>0;i--){int tmp=a[0];//只需要tmp一個額外空間,所以空間複雜度為O(1)a[0]=a[i];a[i]=tmp;max_heapify(a,0,i-1);}for(int i=0;i<ARRAY_SIZE;i++)cout<<a[i]<<endl;system("pause");return 0;}

堆排序時間複雜度為O(nlgn),因為在main中,for為O(n),每次max_heapify調整堆大概要遞迴堆的深度O(lgn),所以總的複雜度為O(nlgn)。

其實初看build_max_heap建堆也要O(nlgn),因為也是迴圈n次,每次lgn,但是因為對於不同的節點,他的高度不一樣,那麼他的在調整max_heapify的時間也不一樣,所以精確計算可知build_max_heap的複雜度只有O(n),具體請看《演算法導論》

聯繫我們

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