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')
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章