Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> C++

Sắp xếp lớn đến nhỏ trong C++


Cho mảng số nguyên nums. Sắp xếp theo quy tắc: phần tử 1 là lớn nhất, phần tử 2 là nhỏ nhất, phần tử 3 là lớn nhì, phần tử 4 là nhỏ nhì, và cứ thế.

Ví dụ: [6,3,10,4] → [10, 3, 6, 4].

Giải thuật:

  • Sắp xếp mảng tăng dần.
  • Dùng hai con trỏ i = 0 (đầu) và j = n-1 (cuối).
  • Lần lượt lấy nums[j--] rồi nums[i++] cho đến khi i > j.

Ví dụ

#include <bits/stdc++.h>
using namespace std;

void print_vector(vector<int> v) {
    cout << "[";
    for (int i = 0; i < v.size(); i++)
        cout << v[i] << ", ";
    cout << "]" << endl;
}

class Solution {
public:
    vector<int> solve(vector<int>& nums) {
        vector<int> ret;
        sort(nums.begin(), nums.end());
        int j = nums.size() - 1, i = 0;
        while (i <= j) {
            ret.push_back(nums[j--]);
            if (i <= j)
                ret.push_back(nums[i++]);
        }
        return ret;
    }
};

int main() {
    Solution ob;
    vector<int> v = {6,3,10,4};
    print_vector(ob.solve(v));
}

Đầu vào

{6,3,10,4}

Đầu ra

10, 3, 6, 4