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