Quick Sort
วาง pivot ในตำแหน่งสุดท้ายแล้ว sort สอง partition แบบ recursion
Quick Sort คืออะไร?
วาง pivot ในตำแหน่งสุดท้ายแล้ว sort สอง partition แบบ recursion
Partition ค่ารอบ pivot
ประเด็นสำคัญ
- ทดสอบ input ว่าง หนึ่งสมาชิก ซ้ำ และเรียงแล้ว
- แยก correctness จาก optimization
- ใช้ standard library ใน production เมื่อเหมาะสม
ภาพจำลอง Quick Sort
O(n log n)กด เล่น หรือ ทีละขั้น เพื่อดูการเปรียบเทียบและการย้ายข้อมูลแต่ละขั้น
ตัวอย่างโค้ด C และ C++
main.c
#include <stdio.h>
void swap(int *left, int *right) {
int temporary = *left;
*left = *right;
*right = temporary;
}
int partition(int *values, int low, int high) {
int pivot = values[high];
int boundary = low;
for (int scan = low; scan < high; ++scan) {
if (values[scan] < pivot) {
swap(&values[boundary++], &values[scan]);
}
}
swap(&values[boundary], &values[high]);
return boundary;
}
void quick_sort(int *values, int low, int high) {
if (low >= high) return;
int pivot = partition(values, low, high);
quick_sort(values, low, pivot - 1);
quick_sort(values, pivot + 1, high);
}
int main(void) {
int values[] = {9, 4, 7, 3, 10, 5};
quick_sort(values, 0, 5);
for (int index = 0; index < 6; ++index) {
printf("%d ", values[index]);
}
}
3 4 5 7 9 10
C++
main.cpp
#include <algorithm>
#include <iostream>
#include <vector>
template<class Iterator>
void quick_sort(Iterator first, Iterator last) {
if (last - first < 2) return;
auto pivot = *(last - 1);
auto middle = std::partition(first, last - 1,
[pivot](int value) { return value < pivot; });
std::iter_swap(middle, last - 1);
quick_sort(first, middle);
quick_sort(middle + 1, last);
}
int main() {
std::vector values{9, 4, 7, 3, 10, 5};
quick_sort(values.begin(), values.end());
for (int value : values) {
std::cout << value << ' ';
}
}
3 4 5 7 9 10
เปรียบเทียบ C และ C++
เฉลี่ย O(n log n) แต่ pivot แย่เป็น O(n²) C++ ใช้ std::partition แสดงขั้นตอน
C
Loop, pointer, length และ buffer เขียนอย่างชัดเจน
C++
Iterator และ algorithm แยก operation จาก storage
แบบฝึกหัด
รันทั้งสองเวอร์ชันแล้วแก้ไขเพื่อสังเกตความแตกต่างของภาษา
- ไล่ตามทุก comparison
- ทดสอบ duplicate และ extreme value
- Benchmark กับ standard library