创建堆并进行堆排序

以下程序是形成小根堆,并进行堆排序。基本操作为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;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值