数据结构 - 排序

完成快速排序,希尔排序,堆排序

/*

10
11 43 97 34 28 92 0 2 343 543 
*/


#include<iostream> 
using namespace std;

void Shell(int a[],int b,int t){//数据,增量,数据个数 
	int tem;
	 for(int i=b;i<t;i++){
	 	if(a[i]<a[i-b]){
	 		tem=a[i];
	 		int j=i-b;
	 		while(a[j]>tem&&j>=0){
	 			a[j+b]=a[j];
	 			j-=b;
			 }
			 a[j+b]=tem;
		 }
	 }
}

void Shellsort(int a[],int b[],int t){
	for(int i=8;i>=0;i--){
		Shell(a,b[i],t);
		//****************************输出 
		cout<<"临时输出"<<"间距为"<<b[i]<<endl;
		for(int i=0;i<t;i++) cout<<a[i]<<' '; 
		cout<<endl;
	}
	
}


int Qsort(int a[],int low,int high){
	int tem=a[low];
	while(low<high){
		while(a[high]>=tem&& high>low) high--;
		a[low]=a[high];
		while(a[low]<=tem && high>low) low++;
		a[high]=a[low];
	}
	a[low]=tem;
	return low;
}
void Quicksort(int a[],int low,int high,int t) {
	if(low<high){
		int mid=Qsort(a,low,high);
		//****************************输出
		cout<<"临时输出此时找到的位置mid为"<<mid<<endl;
		for(int i=0;i<t;i++){
			cout<<a[i]<<' ';
		}
		cout<<endl;
				
		Quicksort(a,low,mid-1,t);
		Quicksort(a,mid+1,high,t);
	}
	
}

void Heapadjust(int a[],int min,int max){//范围 
	int root=min;
	int id=min;
	int tem=a[min];
	for(int i=min*2;i<=max;i*=2){
		if(i<max && a[i]<a[i+1]) i++;
		if(tem>=a[i]) break;
		a[i/2]=a[i];
		id=i;
	}
	a[id]=tem;
}
void Heapsort(int a[],int t){//a[o]不存储数据 ,大顶堆 
	for(int i=t/2;i>=1;i--)
		Heapadjust(a,i,t);
	//****************************	输出
	cout<<"初始大顶堆"<<endl;
	for(int i=1;i<=t;i++){
		cout<<a[i]<<' ';
	}
	cout<<endl;
	cout<<"输出每次排序后的结果如下"<<endl;
	
	int last=t;//最后一个的下标 
	while(1){
		int tem=a[last];
		a[last]=a[1]; 
		a[1]=tem;
		last--;
		Heapadjust(a,1,last);
		if(last==0) break;
		//****************************输出
		
		
		for(int i=1;i<=t;i++){
			cout<<a[i]<<' ';
		}
		cout<<endl;
		
	}
}


void Output(int a[],int t){
	for(int i=0;i<t;i++){
		cout<<a[i]<<endl;
	}
}

int main()
{
	int a[10000]; 
	int t;// 
	int b[15]={1,3,5,7,11,13,19,23,29};
	
	cout<<"希尔排序,请输入数据个数n,和n个数据\n";
	cin>>t;
	for(int i=0;i<t;i++){
		cin>>a[i];
	} 
	Shellsort(a,b,t);
	cout<<"结果是"<<endl;
	Output(a,t);
	
	cout<<"\n快速排序,请输入数据个数n,和n个数据\n"; 
	cin>>t;
	for(int i=0;i<t;i++){
		cin>>a[i];
	}
	Quicksort(a,0,t-1,t); 
	cout<<"结果是"<<endl;
	Output(a,t);
	
	cout<<"\n堆排序,请输入数据个数n,和n个数据\n"; 
	cin>>t;
	for(int i=1;i<=t;i++){
		cin>>a[i];
	}
	Heapsort(a,t);
	
	return 0;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

洛阳八中我最棒

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值