题目内容:
编写一组重载的排序函数,可以对两个整数、三个整数、四个整数、整数数组从大到小排序,函数名为sort,其中数组排序应使用递归的方法,另补充print函数,在一行显示排序后的数组元素。
主函数如下:
int main()
{
int a,b,c,d;
int data[100];
int k,n,i;
cin>>k;
switch(k)
{
case 1:
cin>>a>>b;
sort(a,b);
cout<
#include <iostream>
using namespace std;
void sort(int &a,int &b){
if(a<b){
int tmp = a;
a = b;
b = tmp;
}
}
void sort(int &a,int &b,int &c){
sort(a,b);
sort(a,c);
sort(b,c);
}
void sort(int &a,int &b,int &c,int &d){
sort(a,b,c);
sort(a,d);
sort(b,c,d);
}
// 这一种是使用递归的情况,冒泡排序
void sort(int a[],int n){
if(0<n){
for(int i=0;i<n-1;i++){
sort(a[i],a[i+1]);
}
sort(a,n-1);
}
// 第二种是不使用递归的情况
// for(int i=0;i<n-1;i++){
// for(int j=0;j<n-1-i;j++){
// sort(a[j],a[j+1]);
// }
// }
}
void print(int a[],int n){
for (int i = 0; i < n; i++)
{
if (i==n-1)
{
cout<<a[i];
}else{
cout<<a[i]<<" ";
}
}
cout<<endl;
}
int main(){
int a,b,c,d;
int data[100];
int k,n,i;
cin>>k;
switch(k)
{
case 1:
cin>>a>>b;
sort(a,b);
cout<<a<<" "<<b<<endl;
break;
case 2:
cin>>a>>b>>c;
sort(a,b,c);
cout<<a<<" "<<b<<" "<<c<<endl;
break;
case 3:
cin>>a>>b>>c>>d;
sort(a,b,c,d);
cout<<a<<" "<<b<<" "<<c<<" "<<d<<endl;
break;
case 4:
cin>>n;
for(i=0;i<n;i++){
cin>>data[i];
}
sort(data,n);
print(data,n);
break;
}
return 0;
}