写正确函数需要注意的地方:最大堆的创建与堆排序

void push_down(int* a, int indx,int count)
{
	do 
	{
		int leftindx=indx*2+1;
		int rightindx=leftindx+1;
		//在将indx所指的元素向下压的时候,将左右两个子节点中最大的,并且大于indx本身的向上提。
		//如果没有可以上提的左右子节点,则结束。
		if (leftindx<count && rightindx>=count)
		{
			if (a[indx]<a[leftindx])
			{
				int tmp=a[indx];
				a[indx]=a[leftindx];
				a[leftindx]=tmp;
				indx=leftindx;
			}
			else
				break;
		}
		else if (leftindx<count && rightindx<count)
		{
			if (a[leftindx]>a[rightindx])
			{
				if (a[indx]<a[leftindx])
				{
					int tmp=a[indx];
					a[indx]=a[leftindx];
					a[leftindx]=tmp;
					indx=leftindx;
				}
				else
					break;
			}
			else
			{
				if (a[indx]<a[rightindx])
				{
					int tmp=a[indx];
					a[indx]=a[rightindx];
					a[rightindx]=tmp;
					indx=rightindx;
				}
				else break;
			}
		}
		else
			break;
	} while (indx<count);
}

bool create_heap(int* a, int count)
{
	if (a==NULL)
		return false;
	if(count<0)
		return false;
	if (count==0 || count==1)
	{
		return true;
	}
	for (int i=(count-1)/2;i>=0;--i)
	{
		push_down(a,i,count);
	}
	return true;
}

bool heap_sort(int* a, int count)
{
	if(a==NULL)
		return false;
	if (count<0)
		return false;
	else if(count==0 || count==1)
		return true;

	for (int i=count-1;i>0;--i)
	{
		int t=a[0];
		a[0]=a[i];
		a[i]=t;
		push_down(a,0,i);
	}
	return true;
}

int _tmain(int argc, _TCHAR* argv[])
{
	srand(time(0));
	int size=rand()%4;
	int *head=new int[size];
	generate_n(head,size,genInt);

	copy(head,head+size,ostream_iterator<int>(cout," "));
	cout<<endl;

	if (create_heap(head,size))
	{
		copy(head,head+size,ostream_iterator<int>(cout," "));
		cout<<endl;

		heap_sort(head,size);

		copy(head,head+size,ostream_iterator<int>(cout," "));
		cout<<endl;
	}

	getchar();
	return 0;
}


1.  下压的时候,上提左右子树中最大的,并且大于本身的。

2. 输入输出参数。

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值