Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> C++

วิธีใช้ std::sort เพื่อจัดเรียงอาร์เรย์ใน C++

ในภาษาโปรแกรม การจัดเรียง (sorting) เป็นฟังก์ชันพื้นฐานสำหรับจัดเรียงข้อมูลเป็นลำดับจากน้อยไปมากหรือมากไปน้อย ใน C++ มีฟังก์ชัน std::sort() สำหรับจัดเรียงอาร์เรย์

ไวยากรณ์

sort(start_address, end_address)
  • Start address – ที่อยู่ขององค์ประกอบแรก
  • End address – ที่อยู่ของตำแหน่งต่อจากองค์ประกอบสุดท้าย (one past the end)

โค้ดตัวอย่าง

#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 << "\n The array before sorting is: ";
    display(a);
    sort(a, a + 5); // เรียงจาก a[0] ถึง a[4]
    cout << "\n\n The array after sorting is: ";
    display(a);
    return 0;
}

ผลลัพธ์

The array before sorting is: 4 2 7 9 6
The array after sorting is: 2 4 6 7 9

ข้อมูลเพิ่มเติม:

  • std::sort ใช้ Introsort (hybrid ของ quicksort, heapsort, insertion sort) ความซับซ้อน O(n log n) ใกล้เคียง worst-case
  • สำหรับจัดเรียงจากมากไปน้อย: sort(a, a+5, greater<int>())
  • สำหรับ container อื่น: sort(v.begin(), v.end())
  • C++17 เพิ่ม std::sort แบบ parallel: sort(execution::par, a, a+5)