Insertion Sort is a sorting algorithm that is slightly more efficient than Bubble sort, although both has the same Big O complexity in theory.
The algorithm works by taking each element and inserting it into its correct position within the already sorted portion of the array, continuing this process untill all elements are sorted.
Insertion Sort 與 Bubble sort 相比稍微有效率,但兩者的 Big O 值相同
此演算法藉由不斷將未排序的元素插入到已排序完成的部分內的正確位置,直到所有元素都被排序好
這裡用 小 => 大 排序做說明
跟 Bubble sort 一樣,為 O(n^2)
let unsortedArr = [8, 3, 6, 5, 7, 1];
function insertationSort(arr) {
for (let i = 1; i < arr.length; i++) {
let currentIndex = i;
while (
currentIndex > 0 &&
arr[currentIndex - 1] > arr[currentIndex]
) {
// do swap
[arr[currentIndex - 1], arr[currentIndex]] = [
arr[currentIndex],
arr[currentIndex - 1],];
currentIndex--;
}
}
return arr;
}
console.log(insertationSort(unsortedArr);
insertion sort
https://www.w3schools.com/dsa/dsa_algo_insertionsort.php
insertion sort
https://www.geeksforgeeks.org/insertion-sort-algorithm/
insertion-sort
https://big-o.io/algorithms/comparison/insertion-sort/