堆排序是利用堆的性質, 從縮小的排序空間中不斷的選出堆頂元素,從而達到排序的效果。
堆排序的時間複雜度主要是在不斷的調整堆以滿足堆的性質,其評價性能和最差情況都是O(logN), 平均性能差於快速排序,但最壞情況優於快速排序。
堆可以作爲具有優先級隊列的實現。通常在數據量較大的時候,而需要選擇出前面較大的幾個元素時候, 可以考慮堆排序。
堆排序的實現分爲4步:
1. 初始化堆, 這個過程就是將數組堆化。
2. 選出堆頂元素, 即用待排序空間的最後一個元素和堆頂交換
3. 縮小待排序空間,調整待排序空間,使其滿足堆的性質。
4. 重複2
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#define SIZE 10
#define swap(x, y) do { \
*(x) ^= *(y); \
*(y) ^= *(x); \
*(x) ^= *(y); \
}while(0);
int heap_sort(int*p, int n);
int heap_adjust(int*p, int i, int n);
int gen_random(int*p, int n);
void show(int*p, int n);
int main()
{
int p[SIZE];
gen_random(p, SIZE);
show(p, SIZE);
heap_sort(p, SIZE);
show(p, SIZE);
}
int gen_random(int*p, int n)
{
if(NULL == p)
{
printf("Error: Null pointer\n");
return -1;
}
if(n <= 0)
{
printf("Error: Invalid length\n");
return -1;
}
srand(time(NULL));
while(n>0)
{
p[--n] = rand()%1000;
}
return 0;
}
void show(int*p, int n)
{
int i = 0;
while(i<n)
{
printf("%-4d", p[i++]);
}
printf("\n");
}
int heap_sort(int*p, int n)
{
int i;
// build heap, adjust the not-leaf node
for(i=n/2-1; i>=0; --i)
{
heap_adjust(p, i, n);
}
// select the item
for(i=n-1; i>=1; --i)
{
swap(p, p+i);
heap_adjust(p, 0, i);
}
}
int heap_adjust(int*p, int i, int n)
{
int child, temp;
for( ; 2*i+1 < n; i = child)
{
child = 2 * i + 1;
if( child + 1 < n && p[child + 1] > p[child])
{
++child;
}
if(p[i] < p[child])
{
swap(p+i, p+child);
}
}
}