不知不覺已經來到鐵人賽一半了
加油加油,希望能成功完賽
今天開始 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
圖片來源
這裡用 小 => 大 排序做說明
-
Start 從 dataset 第一個元素開始
Begin with the first element in the dataset (index 0).
-
Compare 將第一個元素與第二個元素作比較
Compare the first element with the second element.
-
Swap 如果第二個值小於第一個值,則兩者交換位置
If the second element is smaller than the first element, swap their positions.
-
Move 移動到下一組元素
Move to the next pair of elements (second and third) and repeat the comparison.
-
Repeat 重複
Continue comparing and swapping until you reach the end of the array.
-
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).
-
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/