思路:
const bubbleSort = function (arr) { for (let i = 0; i < arr.length - 1; i++) { for (let j = 0; j < arr.length - 1 - i; j++) { if (arr[j] > arr[j + 1]) { const temp = arr[j] arr[j] = arr[j + 1] arr[j + 1] = temp } } } return arr }
复杂度 O(n^2)
思路:
const selectionSort = function (arr) { for (let i = 0; i < arr.length - 1; i++) { let indexMin = i for (let j = i; j < arr.length; j++) { if (arr[j] < arr[indexMin]) { indexMin = j } } const temp = arr[i] arr[i] = arr[indexMin] arr[indexMin] = temp } return arr }
复杂度 O(n^2)
思路
const insertSort = function (arr) { for (let i = 1; i < arr.length; i++) { const temp = arr[i] let j = i while (j > 0) { if (arr[j - 1] > temp) { arr[j] = arr[j - 1] } else { break } j-- } arr[j] = temp } return arr }
复杂度 O(n^2)
略好于冒泡和排序算法
思路(分而治之)
const mergeSort = function (arr) { // 递归终点 if (arr.length === 1) return arr // “分” const mid = Math.floor(arr.length / 2) const left = mergeSort(arr.slice(0, mid)) const right = mergeSort(arr.slice(mid)) // “合” const res = [] while (left.length || right.length) { if (left.length && right.length) { res.push(left[0] < right[0] ? left.shift() : right.shift()) } else if (left.length) { res.push(left.shift()) } else if (right.length) { res.push(right.shift()) } } return res }
复杂度 O(nlogn)
其中:分 O(logn) 合 O(n)
思路:
const quickSort = function (arr) { if (arr.length === 1) return arr const left = [], right = [] const mid = arr[0] for (let i = 1; i < arr.length; i++) { if (arr[i] < mid) { left.push(arr[i]) } else { right.push(arr[i]) } } return [...quickSort(left), mid, ...quickSort(right)] }
复杂度 O(nlogn)