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

Sử dụng std::sort để sắp xếp mảng trong C++

std::sort trong <algorithm> sắp xếp dãy theo thứ tự tăng dần (mặc định dùng operator<). Độ phức tạp trung bình O(N log N).

Cú pháp

sort(first_iterator, last_iterator);
  • first_iterator: trỏ đến phần tử đầu tiên.
  • last_iterator: trỏ đến vị trí sau phần tử cuối (past-the-end).

Với mảng C-style: sort(arr, arr + n).

Ví dụ mã

#include <iostream>
#include <algorithm>
using namespace std;

void display(int a[]) {
    for (int i = 0; i < 5; ++i)
        cout << a[i] << " ";
}

int main() {
    int a[5] = {4, 2, 7, 9, 6};
    cout << "Trước sort: ";
    display(a);
    sort(a, a + 5);
    cout << "\nSau sort: ";
    display(a);
    return 0;
}

Kết quả

Trước sort: 4 2 7 9 6
Sau sort: 2 4 6 7 9

Mẹo: Dùng sort(v.rbegin(), v.rend()) hoặc sort(v.begin(), v.end(), greater<int>()) để sắp xếp giảm dần.