iT邦幫忙

2024 iThome 鐵人賽

DAY 16
0

不知不覺已經來到鐵人賽一半了
加油加油,希望能成功完賽

今天開始 sorting 的部分,先從最簡單的 bubble sort 開始

Bubble Sort

Bubble Sort is a simple algorithm for sorting numbers or strings by repeatedly stepping through the list, comparing adjacent elements, and swapping them if they are in the wrong order.

  • It works by "bubbling" the highest (or lowest) values to the top with each pass.
  • Easy to understand and useful for education purposes to demostrate how sorting works.
  • However, due to its inefficiency, with a worst-case time complexity of O(n²), bubble sort is rarely used in practical applications.

Steps of bubble sort


圖片來源

這裡用 小 => 大 排序做說明

  1. Start 從 dataset 第一個元素開始
    Begin with the first element in the dataset (index 0).
  2. Compare 將第一個元素與第二個元素作比較
    Compare the first element with the second element.
  3. Swap 如果第二個值小於第一個值,則兩者交換位置
    If the second element is smaller than the first element, swap their positions.
  4. Move 移動到下一組元素
    Move to the next pair of elements (second and third) and repeat the comparison.
  5. Repeat 重複
    Continue comparing and swapping until you reach the end of the array.
  6. Optimize 當每輪比較結束,最大的元素就會 bubble (像泡泡上浮到最右端),所以下一輪比較中,將範圍遞減1 (因為最後一位元素已被排好,不需被排序)
    After each round, the largest element "bubbles" to its correct position, so in the next round, reduce the comparison range by 1 (skip the last sorted element).
  7. End
    Repeat the process until the array is fully sorted.

Complexity of bubble sort

O(n^2)

Implementation of bubble sort

let unsortedArr = [8, 3, 6, 5, 7, 1];

function bubbleSort(arr) {
    for (let i = arr.length; i > 0; i--) {
        for (let j = 0; j < i; j++) {
            let temp = null;
            if (arr[j + 1] < arr[j]) {
                temp = arr[j + 1];
                arr[j + 1] = arr[j];
                arr[j] = temp;
          }
      }
   }
}


bubbleSort(unsortedArr);
console.log(unsortedArr); // [1,2,3,5,6,7,8]

相關資源

Bubble Sort
https://www.w3schools.com/dsa/dsa_algo_bubblesort.php
Learn Bubble Sort in 7 minutes
https://youtu.be/Dv4qLJcxus8?si=YkQXIDKCctIJQGNv
Bubble Sort
https://www.freecodecamp.org/news/bubble-sort/


上一篇
Coding Practice:Fibonacci sequence & Honai Tower-day15
下一篇
Insertion sort-day17
系列文
演算法與資料結構入門:30天基礎學習之旅30
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言