堆排序

题目:给一个数组进行堆排序

思路:

(1)将无序数组调整成大根堆,从最后一个非叶子结点开始,一直到根,调整时每次都按照一条路径一直到叶子结点

(2)将堆顶和待排序的最后一个元素进行交换,之后再调整堆,使之能够按照从小到大的顺序排列

代码:

#include <iostream>
using namespace std;

//堆排序,大根堆
void HeapAdjust(int* arr,int length,int location)
{
	int nkey = arr[location];

	int nChild = 0;

	while (2*location+1 < length)
	{
		//孩子结点的位子
		nChild = 2*location+1;

		//找最大的孩子
		if (nChild < length-1 && arr[nChild] < arr[nChild+1])
		{
			nChild++;
		}
		//最大孩子与父亲比较
		if (arr[nChild] < nkey)
		{
			break;
		}

		arr[location] = arr[nChild];
		location = nChild;//下一次调整location的位子
	}

	arr[location] = nkey;
}

void HeapSort(int* arr,int length)
{
	//建成大顶堆
	for (int i = (length/2)-1; i >=0; --i)
	{
		HeapAdjust(arr,length,i);
	}

	//排序,按照从小到大的顺序
	for (int j = length-1; j >0; --j)
	{
		swap(arr[j],arr[0]);
		HeapAdjust(arr,j,0);
	}
}

int main()
{
	int nlen;
	cout<<"input array elem number:";
	cin>>nlen;

	int* arr = new int[nlen];

	cout<<"input elem:"<<endl;
	for (int i = 0; i < nlen; ++i)
	{
		cin>>arr[i];
	}

	HeapSort(arr,nlen);

	delete[] arr;
	arr = NULL;
}


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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值