1、算法原理
堆排序的算法主要依據最大堆和最小堆來進行對數據的排序的。首先我們介紹一下堆得概念,堆分爲最大和最小堆。
堆定義:
設n個元素的數據序列{k(0),k(1),...,k(n-1)},當且僅當滿足下列關係
k(i)<=k(2i+1)且k(i)<=k(2i+2) i=0,1,2,....,n/2-1
或
k(i)>=k(2i+1)且k(i)>=k(2i+2) i=0,1,2,....,n/2-1
時,序列{k(0),k(1),...,k(n-1)}稱爲最小堆或者最大堆。
將最小(大)堆看成是一棵完全二叉樹的層次遍歷序列,則任意一個結點的值都小於等於(大於等於)它的孩子結點的值。
堆排序算法的步驟:
(1)創建最大堆
最大堆的構建,簡單的來說就是從完全二叉樹的最底層開始向上調整樹,使其滿足
堆得定義。
(2)堆排序
構建出最大堆之後,根結點值最小。採用選擇排序的思路,每趟將最大值交換到後面,其餘的元素
再調整成最大堆,再選出最大值。循環操作知道排序完成。
2、代碼
/*+++++++++++++++++++++++++++++++++++++
+ 堆排序(C版)
+
+author:zhouyongxyz 2013-4-15 8:46
+++++++++++++++++++++++++++++++++++++*/
#include <cstdio>
typedef int ElementType;
#define LeftChild(i) (2*(i)+1)
#define N 8
void Swap(ElementType &a,ElementType &b);//交換數據
/*
下濾操作,調整堆,每次調用都保證LeftChild(i),
和LeftChild(i)+1的之後的數據都是有序的。
*/
void PercDown(ElementType a[],int i,int n);
void HeapSort(ElementType a[],int n);//堆排序
int main()
{
int a[N]={4,3,5,2,9,7,6,8};
HeapSort(a,N);
for(int i=0;i<N;i++)
printf("%d ",a[i]);
printf("\n");
return 0;
}
void PercDown(ElementType a[],int i,int n)
{
int child;
ElementType 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;
}
void HeapSort(ElementType a[],int n)
{
int i;
for(i=n/2;i>=0;i--) //構建最大堆
PercDown(a,i,n);
for(i=n-1;i>0;i--)
{
Swap(a[0],a[i]);
/*
每次將最大的數交換到最後,使最大堆的元素減少一個,然後繼續
調整,使前面i個數,再次構成最大堆。循環操作
*/
PercDown(a,0,i);
}
}
void Swap(ElementType &a,ElementType &b)
{
ElementType tmp;
tmp=a;
a=b;
b=tmp;
}