一、排序
- 插入算法
let arr = [7, 4, 1, 2, 6, 8, 3, 5, 9] function insertSort (arr) { for (let i = 0; i < arr.length; i++) { let temp = arr[i]; let j = i - 1; while(j >= 0 && arr[j] > temp) { arr[j + 1] = arr[j] j--; } arr[j + 1] = temp; } return arr; } console.log(insertSort(arr))
- 冒泡算法
let arr = [7, 4, 1, 2, 6, 8, 3, 5, 9] function bubbleSort (arr) { for (let i=0; i < arr.length; i++) { for (let j=0; j < arr.length; j++) { if(arr[j] > arr[j+1]) { [arr[j], arr[j+1]] = [arr[j+1], arr[j]]; } } } return arr; } console.log(bubbleSort(arr))
- 选择排序
let arr = [7, 4, 1, 2, 6, 8, 3, 5, 9] function selectSort (arr) { for (let i=0; i<arr.length; i++) { let temp; for (let j = i + 1; j < arr.length; j++) { if (arr[i] > arr[j]) { [arr[i], arr[j]] = [arr[j], arr[i]] } } } return arr; } console.log(selectSort(arr));
- 希尔排序
let arr = [7, 4, 1, 2, 6, 8, 3, 5, 9] function shellSort(arr) { let n = arr.length; let gap = Math.floor(n/2); while(gap >= 1) { for(let i=gap; i < arr.length; i++) { let temp = arr[i]; let j = i; while(j >= gap && arr[j-gap] > temp) { arr[j] = arr[j-gap] j = j-gap; } arr[j] = temp; } gap = Math.floor(gap/2); } return arr; } console.log(shellSort(arr));