五种排序算法
冒泡排序
const bubbleSort = (arr) => { for (let i = 0; i < arr.length; i++) { for (let j = i; j < arr.length; j++) { if (arr[j] < arr[i]) { let cur = arr[j] arr[j] = arr[i] arr[i] = cur } } } return arr }
快速排序
const quickSort = (arr) => { if (arr.length < 2) return arr let mid = Math.floor(arr.length / 2) let midVal = arr.splice(mid, 1)[0] let left = [] let right = [] for (let i = 0; i < arr.length; i++) { if (arr[i] < midVal) { left.push(arr[i]) } else { right.push(arr[i]) } } return quickSort(left).concat([midVal], quickSort(right)) }
选择排序
const selectSort = (arr) => { let min let item for (let i = 0; i < arr.length; i++) { min = i for (let j = i; j < arr.length; j++) { if (arr[j] < arr[min]) min = j } item = arr[min] arr[min] = arr[i] arr[i] = item } return arr }
插入排序
const insertSort = (arr) => { let index let indexVal for (let i = 1; i < arr.length; i++) { index = i indexVal = arr[i] while (index > 0 && arr[index - 1] > indexVal) { arr[index] = arr[index - 1] index-- } arr[index] = indexVal } return arr }
归并排序
function mergeSort (arr) { if (arr.length < 2) return arr let mid = Math.floor(arr.length / 2) let left = arr.slice(0, mid) let right = arr.slice(mid) return merge(mergeSort(left), mergeSort(right)) } function merge (left, right) { let newArr = [] while (left.length > 0 && right.length > 0) { if (left[0] < right[0]) { newArr.push(left.shift()) } else { newArr.push(right.shift()) } } while(left.length) { newArr.push(left.shift()) } while(right.length) { newArr.push(right.shift()) } return newArr }