堆排序

//heapSort.cpp

#include <iostream>
#include <ctime>
#include <cstdlib>
#define NUMBER 9
using namespace std;

struct heapType
{
	int heapArray[NUMBER+1];//数组中存放20个元素,从1到20;
	int arraySize;//数组长度
	int heapSize;//建的堆中元素个数
};

void maxHeapify(heapType &h,int i);//i处保证其满足最大堆的性质
void exchange(int *x,int *y);
void buildMaxHeap(heapType &h);//建堆操作
void heapSort(heapType &h);//堆排序操作
void print(heapType &h);

int main()
{
	heapType heap;
	heap.arraySize = NUMBER;
	heap.heapArray[0] = 0;
	srand(unsigned(time(NULL)));
	for(int i=1;i<=heap.arraySize;i++)
	{
		heap.heapArray[i] = rand()%101;//产生0到100之间的随机数
	}
	cout << "before heapSort:" << endl;
	print(heap);
	heapSort(heap);
	cout << "after heapSort:" << endl;
	print(heap);

	system("pause >> cout");
	return 0;
}

void exchange(int *x,int *y)
{
	int temp = *x;
	*x = *y;
	*y = temp;
}

//最大堆的性质
void maxHeapify(heapType &h,int i)
{
	int l = 2*i;
	int r = 2*i + 1;
	int subscript = i;
	if(l<=h.heapSize && h.heapArray[subscript]<h.heapArray[l])
		subscript = l;
	if(r<=h.heapSize && h.heapArray[subscript]<h.heapArray[r])
		subscript = r;
	if(subscript!=i)
	{
		cout << "echange the " << i << "th :" << h.heapArray[i] 
		       << " and the " << subscript << "th :" << h.heapArray[subscript] 
			   << endl;
		exchange(&h.heapArray[subscript],&h.heapArray[i]);
		maxHeapify(h,subscript);
	}
}

//对堆(二叉树)而言,从第(heapSize/2+1)开始到第n个元素为叶子节点
void buildMaxHeap(heapType &h)
{
	h.heapSize = h.arraySize;
	for(int i=h.heapSize/2;i>=1;i--)
		maxHeapify(h,i);
}

void heapSort(heapType &h)//堆排序操作
{
	cout << "build the maxHeap:" << endl;
	buildMaxHeap(h);//建最大堆
	cout << "begin the heapSort:" << endl;
	//每一次都将h[i]和h[heapsize]互换,然后进行maxHeapify(h)操作,使满足最大堆
	//接着heapSize = heapSize - 1 
	for(int i=h.heapSize;i>=2;i--)
	{
		exchange(&h.heapArray[1],&h.heapArray[i]);
		h.heapSize = h.heapSize - 1;
		maxHeapify(h,1);
	}
}
void print(heapType &h)
{
	for(int i=1;i<=h.arraySize;i++)
		cout << " " << h.heapArray[i];
	cout << endl;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值