การเรียงลำดับแบบ Bubble Sort: เปรียบเทียบคู่ที่อยู่ติดกันแล้วสลับที่กันถ้าอยู่ผ่านลำดับ ทำซ้ำจนเรียบร้อย
ตัวอย่างโค้ด
const arr = [4, 56, 4, 23, 8, 4, 23, 2, 7, 8, 8, 45];
const swap = (items, firstIndex, secondIndex) => {
const temp = items[firstIndex];
items[firstIndex] = items[secondIndex];
items[secondIndex] = temp;
};
const bubbleSort = items => {
const len = items.length;
for (let i = len - 1; i >= 0; i--) {
for (let j = 1; j <= i; j++) {
if (items[j] < items[j - 1]) {
swap(items, j, j - 1);
}
}
}
return items;
};
console.log(bubbleSort(arr));
ผลลัพธ์
[ 2, 4, 4, 4, 7, 8, 8, 8, 23, 23, 45, 56 ]
การวิเคราะห์
| คุณสมบัติ | ค่า |
|---|---|
| Time Complexity | O(n²) - ช้า สำหรับข้อมูลมาก |
| Space Complexity | O(1) - in-place |
| Stable | ใช่ (ค่าเท่ากันไม่สลับที่) |
การปรับปรุง (Optimized Bubble Sort)
const bubbleSortOptimized = arr => {
const n = arr.length;
for (let i = 0; i < n - 1; i++) {
let swapped = false;
for (let j = 0; j < n - 1 - i; j++) {
if (arr[j] > arr[j + 1]) {
[arr[j], arr[j + 1]] = [arr[j + 1], arr[j]];
swapped = true;
}
}
if (!swapped) break; // เรียงแล้ว หยุดก่อนเวลา
}
return arr;
};