堆排序的实现 C++

//============================================================================
// Name        : MyHeap.cpp
// Author      : 
// Version     :
// Copyright   : Your copyright notice
// Description : Hello World in C++, Ansi-style
//============================================================================
堆排序,首先得用O(n)时间复杂度构建一个堆,然后每一次从堆中删除最大的元素,重新调整堆,(nlogn)
#include <iostream>
#include <stdlib.h>
using namespace std;
void modify(int* a,int location, int size){
	if(location<=size/2){
		int leftchild = location*2;
		int rightchild = location*2+1;
		int max = location;
		if(leftchild<=size&&a[leftchild]>a[max])
			max=leftchild;
		if(rightchild<=size&&a[rightchild]>a[max])
			max=rightchild;
		if(max!=location){
			swap(a[location],a[max]);
			modify(a,max,size);
		}
	}else
		return;

}
void buildheap(int*a,int size){
	for(int i =size/2;i>=1;i--){
		modify(a,i,size);
	}
}
void heapsort(int *a,int size){
	buildheap(a,size);
	for(int i =size;i>=1;i--){
		swap(a[1],a[i]);
		modify(a,1,i-1);
	}

}
int main() {
//	cout << "!!!Hello World!!!" << endl; // prints !!!Hello World!!!
	int a[100]={0};
	int size;
	bool flag = true;
	cout<<"welcome to heap sort"<<endl;
	while(flag){
	cout<<"input heap size:";
	cin>>size;
	cout<<"before sort  "<<endl;
	for(int i =1;i<=size;i++)
	{
		a[i]=rand()%100;
		cout<<a[i]<<"   ";
//		if(i%10==0)
//			cout<<endl;
	}
	cout<<endl;
	heapsort(a,size);
	cout<<"after sort  "<<endl;
	for(int i =1;i<=size;i++)
	{
		cout<<a[i]<<"   ";
//		if(i%10==0)
//			cout<<endl;
	}
	cout<<endl;
	if(size==100)
		flag=false;
	}
	return 0;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值