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

Strand Sort ใน C++

ในส่วนนี้เราจะดูวิธีจัดเรียง (sort) อาร์เรย์หรือ linked list โดยใช้ standard library ของ C++ มี library หลายตัวสำหรับวัตถุประสงค์ต่างๆ การจัดเรียงเป็นหนึ่งในนั้น

ฟังก์ชัน C++ std::list::sort() จัดเรียงสมาชิกของ list ในลำดับขึ้น (ascending) ลำดับของสมาชิกที่เท่ากันจะถูกเก็บรักษา (stable) ใช้ operator< สำหรับการเปรียบเทียบ

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

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

int main(void) {
    list<int> l = {1, 4, 2, 5, 3};
    cout << "Contents of list before sort operation" << endl;
    for (auto it = l.begin(); it != l.end(); ++it)
        cout << *it << endl;
    l.sort();
    cout << "Contents of list after sort operation" << endl;
    for (auto it = l.begin(); it != l.end(); ++it)
        cout << *it << endl;
    return 0;
}

ผลลัพธ์

Contents of list before sort operation
1
4
2
5
3
Contents of list after sort operation
1
2
3
4
5