完成快速排序,希尔排序,堆排序
/*
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;
}