华为机试HJ101:对数组元素按照升序或降序进行排序

简介: 华为机试HJ101:对数组元素按照升序或降序进行排序

题目描述:

输入整型数组和排序标识,对其元素按照升序或降序进行排序

输入描述:

第一行输入数组元素个数

第二行输入待排序的数组,每个数用空格隔开

第三行输入一个整数0或1。0代表升序排序,1代表降序排序

输出描述:

输出排好序的数字

示例:

输入:

8

1 2 4 9 3 55 64 25

0


输出:

1 2 3 4 9 25 55 64

解题思路:

这题比较简单。cmpdes用来降序,cmpasc用来升序,对vector容器的内容进行sort排序,升序降序由输入决定,解决。

测试代码:

#include <iostream>
#include <algorithm>
#include <vector>
using namespace std;
// 降序
bool cmpdes(int a,int b)
{
    return a>b;
}
//升序
bool cmpasc(int a,int b)
{
    return a<b;
}
int main()
{
    int num;
    while(cin>>num)
    {
        vector<int> v;
        for(int i=0;i<num;++i)
        {
            int temp;
            cin>>temp;
            v.push_back(temp);
        }
        int flag;
        cin>>flag;
        if(flag)
        {
            sort(v.begin(),v.end(),cmpdes);
        }
        else{
            sort(v.begin(),v.end(),cmpasc);
        }
        for(auto i:v)
        {
            cout<<i<<" ";
        }
        cout<<endl;
    }
    return 0;
}
相关文章
|
21天前
数组排序,实现升序和降序,输出最大值最小值
数组排序,实现升序和降序,输出最大值最小值
21 2
|
21天前
leetcode-4:寻找两个正序数组的中位数
leetcode-4:寻找两个正序数组的中位数
20 0
|
21天前
|
算法 搜索推荐 API
LeetCode 912. 排序数组
LeetCode 912. 排序数组
30 0
|
21天前
|
算法
leetcode-寻找两个正序数组的中位数
leetcode-寻找两个正序数组的中位数
26 0
|
11月前
了解冒泡排序,并写出一个函数进行排序,拍成升序
了解冒泡排序,并写出一个函数进行排序,拍成升序
|
12月前
|
搜索推荐 Java
Leecode912. 排序数组
Leecode912. 排序数组
37 0
|
算法
LeetCode 4. 寻找两个正序数组的中位数
LeetCode 4. 寻找两个正序数组的中位数
81 0
LeetCode 4. 寻找两个正序数组的中位数
leetcode 912 排序数组
leetcode 912 排序数组
62 0
leetcode-4. 寻找两个正序数组的中位数
时间复杂度:O(n) 其中n表示的是两个有序数组合并后的排序时间
55 0
leetcode-4. 寻找两个正序数组的中位数
LeetCode 1636. 按照频率将数组升序排序
给你一个整数数组 nums ,请你将数组按照每个值的频率 升序 排序。
55 0

热门文章

最新文章