堆排序(《编程珠玑》第14章)

下面是堆排序的代码,其中在《编程珠玑》第14章中的代码,在建堆时候用的是从下往上的上虑,而习题2也指出了从下往上的下虑的复杂度更低,能够在O(n)复杂度内完成建堆。

#include<iostream>
#include<algorithm>
using namespace std;
void siftUp(int *A,int n)
{
	int curr=n-1;
	while(curr)
	{
		int temp=(curr-1)>>1;
		if(A[temp]>A[curr])
		{
			swap(A[temp],A[curr]);
			curr=temp;
		}
		else
			return;
	}
}
void siftDown(int *A,int n,int num)
{
	int curr=num;
	while(curr<=(n-2)>>1)
	{
		int left=2*curr+1,right=2*curr+2;
		int result=left;
		if(right<n && A[left]>A[right])//注意此处right的界限
			result=right;
		if(A[curr]>A[result])
		{
			swap(A[curr],A[result]);
			curr=result;
		}
		else
			return;
	}
}

void buildHeap(int A[],int n)
{
	for(int i=(n-2)>>1;i>=0;i--)
		siftDown(A,n,i);
}
void heapSort(int *A,int n)
{
	buildHeap(A,n);
	for(int i=0;i<n;i++)
	{
		swap(A[0],A[n-1-i]);
		siftDown(A,n-1-i,0);
	}
}

int genRand()
{
	return rand()%100;
}

int main()
{
	const int N=15;
	int A[N];
	generate(A,A+N,genRand);
	heapSort(A,N);

	system("pause");
	return 0;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值