以下程序是形成小根堆,并进行堆排序。基本操作为head_shift_down()函数,该函数将大的元素往下降。
创建堆和进行堆排都是通过它来完成。
编写过程出现一些错误就是进行终止时使用的判断条件为 data[smaller] >= data[index];应该为data[smaller] >= tmp;tmp即为要shiftdown的元素。
而对index进行下一步,应是index = smaller,而不是index = index * 2 + 1;index = index * 2 + 1;只是左边的。
另外二叉树中我使用的数组 下标为0到size-1.也就是左孩子节点下标为2*index+1。
//
// author: kangquan2008@scut
//
// blog:http://blog.csdn.net/kangquan2008
//
// description: creats a small heap,
// and sorts the datas from small to big.
//
/
#include <stdio.h>
#include <stdlib.h>
/*
* I'm accustomed to set the index of array from 0 to size-1.
* And this function will shift the smallest data on the top,
* which we call small heap.
*/
void heap_shift_down(int data[],int index,int size)
{
int tmp = data[index];
int smaller = 0;
/* still can shift down,at this moment,data[index] has a left node definitely*/
while(index < size / 2)
{
int left = 2*index + 1;
int right = left + 1;
if(right < size && data[right] < data[left])
{
smaller = right;
}else{
smaller = left;
}
/*error,should notice that can not be data[index],should smaller than tmp!!!*/
//if(data[smaller] >= data[index] )
/*ok*/
if(data[smaller] >= tmp)
break;
data[index] = data[smaller];
/*should be the index of data[smaller]*/
//index = index * 2 + 1;
index = smaller;
}
data[index] = tmp;
}
void create_heap(int data[],int size)
{
for(int i = size/2-1; i>=0; i-- )
{
heap_shift_down(data,i,size);
}
}
int heap_sort(int data[],int size)
{
int tmp = data[0];
data[0] = data[size-1];
heap_shift_down(data,0,size-1);
return tmp;
}
void display(int data[],int size)
{
for(int i=0; i<size; i++)
{
printf("%d ",data[i]);
}
printf("\n");
}
int main()
{
int data[] = {10,2,22,9,4,3,7};
int size = sizeof(data)/sizeof(data[0]);
printf("raw datas :\t");
display(data,size);
printf("form a heap:\t");
create_heap(data,size);
display(data,size);
printf("heap sorted:\t");
for(int i=size; i>0; i--)
{
printf("%d ",heap_sort(data,i));
}
printf("\n");
return 0;
}