码迷,mamicode.com
首页 > 其他好文 > 详细

堆/堆排序

时间:2014-08-26 13:48:06      阅读:187      评论:0      收藏:0      [点我收藏+]

标签:堆排序

<h1>原理参考:http://blog.csdn.net/morewindows/article/details/6709644</h1>
/**********************************************************/
//堆插入
void MinHeapfixup(int a[],int n,int num){

	a[n] = num;
	int j,temp;
	temp = num;
	j = (n-1)/2;
	while (j >= 0 && n != 0)
	{
		if(temp >= a[j])
			break;
		a[n] = a[j];
		n = j;
		j = (n-1)/2;
	}
	a[j] = temp;
}
//堆删除
void MinHeapfixdown(int a[],int i,int n){
	int j,temp;
	temp = a[i];
	j = 2*i + 1;

	while (j < n)
	{
		if(j+1 < n && a[j+1] < a[j])
			++j;
		if(temp <= a[j])
			break;
		a[i] = a[j];
		i = j;
		j = 2*i +1;
	}
	a[i] = temp;
}
void HeapDelete(int a[],int n){

	swap(a[0],a[n-1]);
	MinHeapfixdown(a,0,n-1);
}

//数组堆化
void MakeHeap(int a[],int n){
	for (int i = n/2-1; i>=0; --i)
	{
		MinHeapfixdown(a,i,n);
	}
}
//堆排序
void HeapSort(int a[],int n){

	for (int i=n-1; i>=1; --i)
	{
		swap(a[0],a[i]);
		MinHeapfixdown(a,0,i);
	}
}

int _tmain(int argc, _TCHAR* argv[])
{
	int a[] = {9,12,17,30,50,20,60,65,4,19};
	int i = 0;
	cout<<"原数组"<<endl;
	while (i<10)
	{
		cout<<a[i]<<" ";
		++i;
	}
	cout<<endl;
	MakeHeap(a,10);
	i = 0;
	cout<<"数组堆化"<<endl;
	while (i<10)
	{
		cout<<a[i]<<" ";
		++i;
	}
	cout<<endl;
	HeapSort(a,10);
	i = 0;
	cout<<"堆化后排序"<<endl;
	while (i<10)
	{
		cout<<a[i]<<" ";
		++i;
	}
	system("pause");
	return 0;
}

bubuko.com,布布扣




堆/堆排序

标签:堆排序

原文地址:http://blog.csdn.net/h_wlyfw/article/details/38845437

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!