之前看其他算法和數據結構書的時候覺得堆排序的代碼比較難寫,今天看過《算法導論》發現也不是那麼難,所以就動手自己寫了一個。原理就是根據算法導論第三版堆排序僞代碼而來的。
#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都多加了1
int largest;
if(l<=heap_size&&a[l]>a[pos])
largest=l;
else
largest=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),具體請看《算法導論》