堆排序C++源码

堆排序的思想:
1.初始化创建堆,然后重复步骤2,3
2.交换堆顶和堆得最后一个元素,并缩小堆的大小

3.调整堆,即保证待排序的数组部分始终满足堆的结构


/*******************************************************/
/* this program is used to do a heap sort              */
/* Author: SaoNian                                     */
/* Time: 2012/11/11                                    */
/*******************************************************/
//#include <iostream>
#include <time.h>
#include <stdlib.h>
#include <iomanip.h>
//using namespace std;

int * generateArray(int n);//generate an unsorted array with length n
void buildHeap(int *a,int n);//build a to be a heap 
void max_heapify(int *a,int i,int length);//to Adjust the heap
void heapSort(int *a,int n);//heapSort
void showArray(int *a,int n);
int main()
{
	int * arr=generateArray(30);
	cout<<"the unsort Array:"<<endl;
	showArray(arr,30);
	heapSort(arr,30);
	cout<<"now we Sort it:"<<endl;
	showArray(arr,30);
	return 0;
}
int * generateArray(int n)
{
	int i;
	int * arr=new int[n+1];
	srand((int)time(NULL));
	for(i=1;i<=n;i++)
	{
		arr[i]=rand()%n;
	}
	return arr;
}
void showArray(int *a,int n)
{
	int i=1;
	for(;i<=n;i++)
	{
		cout<<setw(4)<<a[i];
		if(i%10==0)
		{
			cout<<endl;
		}
	}
}
void heapSort(int *a,int n)
{
	buildHeap(a,n);
	for(int i=n;i>=2;i--)
	{
		int tmp=a[1];
		a[1]=a[i];
		a[i]=tmp;
		max_heapify(a,1,i-1);
	}
}

void max_heapify(int *a,int i,int length)
{
	int left=2*i;
	int right=2*i+1;
	int maxPos=i;
	if(left<=length)
	{
		if(a[left]>=a[i])
		{
			maxPos=left;
		}
	}
	if(right<=length)
	{
		if(a[right]>=a[maxPos])
		{
			maxPos=right;
		}
	}
	if(maxPos!=i)
	{
		int tmp=a[maxPos];
		a[maxPos]=a[i];
		a[i]=tmp;
		max_heapify(a,maxPos,length);
	}
}

void buildHeap(int *a,int n)
{
	int i=n/2;
	for (;i>=1;i--)
	{
		max_heapify(a,i,n);
	}
}


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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值