排序函数重载

题目内容:
编写一组重载的排序函数,可以对两个整数、三个整数、四个整数、整数数组从大到小排序,函数名为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;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值