堆排序是O(N*logN),经验中它是一个稳定的排序算法,实际中慢于希尔排序。
#include "stdafx.h"
#include "stdio.h"
#define LeftChild( i ) ( 2 * ( i ) + 1)
void Swap(int* a1, int* a2)
{
int temp = *a1;
*a1 = *a2;
*a2 = temp;
}
void PercDown(int A[], int i, int count)
{
int child;
int temp;
for( temp = A[i]; LeftChild(i) < count; i = child )
{
//左儿子
child = LeftChild(i);
//没有到最末尾,右儿子大于左儿子,则指向右儿子
if( child != count - 1 && A[child+1] > A[child] )
child++;
if( temp < A[child] )//如果小于儿子,则儿子上浮
A[i] = A[child];
else
break;//大于儿子则放入堆中
}
A[i] = temp;//数据进入堆中
}
void HeapSort(int A[], int count)
{
int i;
//建立一个堆
for( i = count / 2; i >= 0; i-- )
{
PercDown(A, i, count);//插入到堆中
for( int j = 0; j < count; j++ )
printf("%d ", A[j]);
printf("/n");
}
for( i = count - 1; i > 0; i-- )
{
//下标0为最大值,放置到数组末尾,然后将下标0插入到堆中
Swap( &A[0], &A[i] );
PercDown(A, 0, i);
}
}
int _tmain(int argc, _TCHAR* argv[])
{
int A[] = { 12, 45, 98, 68, 37, 6, 21, 88};
int count = sizeof(A) / sizeof(A[0]);
HeapSort(A, count);
for( int i = 0; i < count; i++ )
printf("%d ", A[i]);
return 0;
}