1. Bubble sort, selection sort
Bubble sorting and selection sorting are the simplest sorting algorithms. Both of them sort an array through two layers of loops. Their application scenarios are rare, but it is necessary to understand the ideas of these two algorithms.
2. Core idea
Bubble sort: 边比较边替换
selection sort:先拿最小索引、再替换
3. Case study
Bubble Sort:
function BubbleSort(arr) {
let len = arr.length - 1;
for (let i = 0; i < len; i ++ ) {
// 边比较边替换
for (let j = 0; j < len; j ++) {
if (arr[j] > arr[j+1]) {
[arr[j], arr[j+1]] = [arr[j+1], arr[j]]
}
}
}
}
let arr = [2, 4, 1, 5]
BubbleSort(arr)
Select sort:
function SelectionSort(arr) {
let len = arr.length - 1
let minIndex = 0
for (let i = 0; i < len; i ++) {
for (let j = 0; j < len; j ++) {
if (arr[j] < arr[j+1]) {
// 拿到最小索引
minIndex = j
}
}
// 再替换
[arr[i], arr[minIndex]] = [arr[minIndex], arr[i]]
}
}
let arr = [2, 4, 1, 5]
SelectionSort(arr)