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

การเรียงลำดับแบบ Bubble Sort - JavaScript

การเรียงลำดับแบบ 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 ComplexityO(n²) - ช้า สำหรับข้อมูลมาก
Space ComplexityO(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;
};