การจัดเรียง Vector ใน C++ ทำได้ด้วย std::sort() ใน <algorithm> สำหรับ Stable Sort ใช้ std::stable_sort รักษาลำดับสัมพัทธ์ของสมาชิกเท่ากัน สามารถใช้ Quicksort, Mergesort ได้ตามต้องการ
จัดเรียงจากมากไปน้อย (Descending) ใช้ std::greater<>()
อัลกอริทึม
Begin
Declare vector v with values
Print "Elements before sorting"
Print all elements
Print "Elements after sorting"
Call sort(v.begin(), v.end(), greater<>()) for descending
Print all elements
End.ตัวอย่าง
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
int main() {
vector<int> v = {10, 9, 8, 6, 7, 2, 5, 1};
cout << "Elements before sorting" << endl;
for (const auto &i : v) cout << i << ' ' << endl;
cout << "Elements after sorting" << endl;
sort(v.begin(), v.end(), greater<>());
for (const auto &i : v) cout << i << ' ' << endl;
return 0;
}ผลลัพธ์
Elements before sorting 10 9 8 6 7 2 5 1 Elements after sorting 10 9 8 7 6 5 2 1