计算机考研复试上机题 —— 特殊排序 (华中科技大学)

 

思路:

  1. 使用C++自带的sort方法将数组所有数据升序排序;

  2. 挑出最大的一个元素,剩余按照题目要求输出;

C++代码:

#include<iostream>
//sort头文件 
#include<algorithm> 

using namespace std;

//全局变量数组 
int array[1005];

//sort辅助判断函数 
bool compare(int a, int b) {
    return a < b;
}

//处理函数 
void solve(int n) {
    int count = 0;
    for(int i=0; i<n; i++) {
        cin>> array[i];
        count++;
    }
    //数组按照升序排序 
    sort(array, array+count, compare);
    //输出最大的一个元素 
    cout<< array[count-1]<< endl;
    //去除一个元素后发现没有元素 
    if(count < 2) {
        cout<< "-1\n";
    }else {
        for(int i=0; i<n-1; i++) {
            if(i != 0) {
                cout<< " ";
            }
            cout<< array[i];
        }
        cout<< endl;
    }
}

int main() {
    int n;
    //多组数据输入 
    while(cin>> n) {
        solve(n);
    }
    
    return 0;
}

猜你喜欢

转载自www.cnblogs.com/Lunix-touch/p/12295404.html
今日推荐