您的位置:首页 > 其它

内部排序算法之堆排序

2014-04-01 17:12 155 查看
堆排序是利用堆的性质, 从缩小的排序空间中不断的选出堆顶元素,从而达到排序的效果。

堆排序的时间复杂度主要是在不断的调整堆以满足堆的性质,其评价性能和最差情况都是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);
}
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐