Bubble Sort
แต่ละ pass ดันค่ามากสุดที่ยังไม่เรียงไปท้าย
Bubble Sort คืออะไร?
แต่ละ pass ดันค่ามากสุดที่ยังไม่เรียงไปท้าย
เรียงโดยสลับคู่ที่อยู่ผิดลำดับ
ประเด็นสำคัญ
- ทดสอบ input ว่าง หนึ่งสมาชิก ซ้ำ และเรียงแล้ว
- แยก correctness จาก optimization
- ใช้ standard library ใน production เมื่อเหมาะสม
ภาพจำลอง Bubble Sort
O(n²)กด เล่น หรือ ทีละขั้น เพื่อดูการเปรียบเทียบและการย้ายข้อมูลแต่ละขั้น
ตัวอย่างโค้ด C และ C++
main.c
#include <stdio.h>
int main(void) {
int values[] = {5, 1, 4, 2};
for (int end = 3; end > 0; --end) {
int changed = 0;
for (int index = 0; index < end; ++index) {
if (values[index] > values[index + 1]) {
int temporary = values[index];
values[index] = values[index + 1];
values[index + 1] = temporary;
changed = 1;
}
}
if (!changed) break;
}
for (int index = 0; index < 4; ++index) {
printf("%d ", values[index]);
}
}
1 2 4 5
C++
main.cpp
#include <iostream>
#include <vector>
int main() {
std::vector values{5, 1, 4, 2};
for (auto end = values.end(); end != values.begin(); --end) {
bool changed = false;
for (auto item = values.begin(); item + 1 != end; ++item) {
if (*item > *(item + 1)) {
std::iter_swap(item, item + 1);
changed = true;
}
}
if (!changed) break;
}
for (int value : values) {
std::cout << value << ' ';
}
}
1 2 4 5
เปรียบเทียบ C และ C++
เหมาะกับการเรียนแต่เป็น O(n²) early exit ทำให้ input เรียงแล้วเป็น O(n) และ production C++ มักใช้ std::sort
C
Loop, pointer, length และ buffer เขียนอย่างชัดเจน
C++
Iterator และ algorithm แยก operation จาก storage
แบบฝึกหัด
รันทั้งสองเวอร์ชันแล้วแก้ไขเพื่อสังเกตความแตกต่างของภาษา
- ไล่ตามทุก comparison
- ทดสอบ duplicate และ extreme value
- Benchmark กับ standard library