堆排序方法主要是循环的将要排序的数据构造成堆,然后将堆顶输出
循环利用上述方法,将剩下的数据继续构造成堆。
该方法的时间复杂度为nlogn. 空间复杂度为O(1);
#include <stdio.h>
void dump_heap(int *list, int len)
{
int i = 0;
for (i = 1; i <= len; i++)
printf("%d ", list[i]);
printf("\n");
}
void create_heap(int *heap, int root, int len)
{
int i, j;
int temp;
int finish = 0;
j = 2*root;
temp = heap[root];
while( j <= len && finish ==0)
{
/*找最大子节点*/
if(j < len)
{
if (heap[j] < heap[j + 1])
j++;
}
if(temp >= heap[j])
{
finish = 1;
}
else
{
heap[j/2] = heap[j];
j = 2*j;
}
heap[j/2] = temp;
}
}
void heap_sort(int *heap, int len)
{
int i, j, temp;
/*二叉树转成heap*/
for (i = len/2; i > 0; i--)
{
create_heap(heap, i, len);
dump_heap(heap, len);
}
/*开始排序*/
for (i = len - 1; i > 0; i--)
{
temp = heap[i+1];
heap[i+1] = heap[1];
heap[1] = temp;
create_heap(heap, 1, i);
printf("cur state: ");
dump_heap(heap, len);
}
}
int main(int argc, char* argv[])
{
//第一个数据为空位置,不存储数据,主要是为了方便构造树。
int list[] = {0, 1,3,89,3,5,67,25,88,55,43,7,9,10};
heap_sort(list, sizeof(list)/sizeof(list[0]) - 1);
return 0;
}
修改为下面的程序,更好一点
#include <stdio.h>
void dump_heap(int *list, int len)
{
int i = 0;
for (i = 1; i <= len; i++)
printf("%d ", list[i]);
printf("\n");
}
void create_heap(int *heap, int root, int len)
{
int j;
int temp;
temp = heap[root];
for (j = 2*root; j <= len; j *= 2)
{
/*找最大子节点*/
if(j < len && heap[j] < heap[j+1])
j++;
if(temp >= heap[j])
break;
else
{
heap[root] = heap[j];
root = j;
heap[j] = temp;
}
}
}
void heap_sort(int *heap, int len)
{
int i, j, temp;
/*二叉树转成heap*/
for (i = len/2; i > 0; i--)
{
create_heap(heap, i, len);
dump_heap(heap, len);
}
/*开始排序*/
for (i = len - 1; i > 0; i--)
{
temp = heap[i+1];
heap[i+1] = heap[1];
heap[1] = temp;
create_heap(heap, 1, i);
printf("cur state: ");
dump_heap(heap, len);
}
}
int main(int argc, char* argv[])
{
int list[] = {0, 1,3,89,3,5,67,25,88,55,43,7,9,10};
heap_sort(list, sizeof(list)/sizeof(list[0]) - 1);
return 0;
}