js常用的几种排序

function testArr() {
  return [0, 2, 9, 7, 35, 87, 96, 8, 47, 1]
}
/** 原生方法排序 */
function nativeSort(arr) {
  return arr.sort((a, b) => a - b)
}
const arr1 = testArr()
console.time('nativeSort')
console.log(nativeSort(arr1))
console.timeEnd('nativeSort')
/** 选择排序 */
function selectionSort(arr) {
  let len = arr.length
  if (arr.length < 2) return arr
  let max = 0 /** 最大值下标 */
  for (let i = 0; i < len; i++) {
    const subLen = len - i
    for (let j = 1; j < subLen; j++) {
      if (arr[j] > arr[max]) max = j
      if (subLen - 1 === j) {
        ;[arr[j], arr[max]] = [arr[max], arr[j]]
        max = 0
      }
    }
  }
  return arr
}
const arr2 = testArr()
console.time('selectionSort')
console.log(selectionSort(arr2))
console.timeEnd('selectionSort')
/** 快排 */
function quickSort(arr) {
  let len = arr.length
  if (len < 2) return arr
  let init = arr[0]
  let left = []
  let right = []
  for (let i = 1; i < len; i++) {
    if (arr[i] > arr[0]) {
      right.push(arr[i])
    } else {
      left.push(arr[i])
    }
  }
  return [...quickSort(left), init, ...quickSort(right)]
}
const arr3 = testArr()
console.time('quickSort')
console.log(quickSort(arr3))
console.timeEnd('quickSort')
/** 冒泡 */
function bubbleSort(arr) {
  let len = arr.length
  if (len < 2) return arr
  for (let i = 0; i < len; i++) {
    /** ·len - 1 - i· 减`1`是因为arr[j+1]会超出长度,减`i`是优化数组尾部不必要的比较*/
    for (let j = 0; j < len - 1 - i; j++) {
      if (arr[j] > arr[j + 1]) {
        ;[arr[j], arr[j + 1]] = [arr[j + 1], arr[j]]
      }
    }
  }
  return arr
}
const arr4 = testArr()
console.time('bubbleSort')
console.log(bubbleSort(arr4))
console.timeEnd('bubbleSort')
/** 插入排序 */
function insertionSort(arr) {
  var len = arr.length
  var preIndex, current
  for (var i = 1; i < len; i++) {
    preIndex = i - 1
    current = arr[i]
    while (preIndex >= 0 && arr[preIndex] > current) {
      arr[preIndex + 1] = arr[preIndex]
      preIndex--
    }
    arr[preIndex + 1] = current
  }
  return arr
}
const arr5 = testArr()
console.time('insertionSort')
console.log(insertionSort(arr5))
console.timeEnd('insertionSort')

你可能感兴趣的:(javascript)