如何在没有 if 语句的情况下从最小到最大对一组整数进行排序?

How do I order a set of integers from smallest to greatest without if statements?

我目前遇到一个 C++ 问题,要求我将五个输入的整数从小到大排序。我试过使用 if 语句来执行此操作,但列出所有可能的组合似乎效率太低。我也尝试过 min 和 max 函数,但它们只适用于最小和最大的两个整数。最快的排序方法是什么?

#include <iostream>
using namespace std;

int main() {

    cout << "Enter five integers. \n\n>";
    int a, b, c, d, e;
    cin >> a >> b >> c >> d >> e;

    int first = min({a, b, c, d, e});
    int fifth = max({a, b, c, d, e});

    cout << first << fifth << "\n"; //This is where I want to output the middle three integers in order

    cout << "\n";
    return 0;
}

到目前为止,这是我的代码。 ^

标准库有一个叫做std::sort的函数,它适用于任何范围。您可以将数字放在一个数组中,也可以将它们放在其他一些容器中(例如 std::vector)。在这种情况下,考虑到五项限制,数组就足够简单了。例如:

#include <iostream>
#include <algorithm>
#include <array>
#include <iterator>

int main() {
    std::array<int, 5> numbers;

    std::cout << "Enter five integers. \n\n>";

    // Read numbers into array.
    for (auto & i : numbers) {
        std::cin >> i;
    }

    // Sort the entire array.
    std::sort(std::begin(numbers), std::end(numbers));

    // Display sorted numbers.
    for (auto i : numbers) {
        std::cout << i << '\n';
    }

    return 0;
}

这里最大的错误是将值读入单个变量。 C++ 有许多不同的容器可以容纳多个值:数组、std::vectorstd::array。但是有一个有魔法 属性,它始终保持所有项目的排序顺序:std::multiset.

cout << "Enter five integers. \n\n>";
std::multiset<int> a;
for (int i = 0; i < 5; ++i)
{
    int v;
    cin >> v;
    a.insert(v);
}
for (auto it = a.begin(); it != a.end(); ++it)
    cout << *it;
cout << "\n";

您可以使用 std::vector 存储输入,然后使用 std::sort 对元素进行排序。

#include <iostream>
#include <algorithm>
#include <vector>

using namespace std;

int main(){
    vector <int> nums(5);
    
    for(int i = 0; i < 5; ++i){
        cin >> nums[i];
    }

    sort(nums.begin(), nums.end());
}

替代 std::sort,您可以使用 std::multiset 对元素进行排序:

#include <iostream>
#include <fstream>
#include <cmath>
#include <algorithm>
#include <vector>
#include <set>

using namespace std;

int main(){
    multiset <int> nums;
    int input;
    
    for(int i = 0; i < 5; ++i){
        cin >> input;
        nums.insert(input);
    }
}