JavaScript实现5大基础排序算法

108 阅读1分钟

1. 冒泡排序

Array.prototype.bubbleSort = function () {
  for (let i = 0; i < this.length - 1; i++) {
    for (let j = 0; j < this.length - 1 - i; j++) {
      if (this[j] > this[j + 1]) {
        let temp = this[j]
        this[j] = this[j + 1]
        this[j + 1] = temp
      }
    }
  }
}

2. 选择排序

Array.prototype.selectSort = function () {
  for (let i = 0; i < this.length - 1; i++) {
    let minIndex = i
    for (let j = i; j < this.length - 1; j++) {
      if (this[minIndex] > this[j]) {
        minIndex = j
      }
    }
    let temp = this[i]
    this[i] = this[minIndex]
    this[minIndex] = temp
  }
}

3. 插入排序

Array.prototype.insertSort = function () {
  for (let i = 1; i < this.length - 1; i++) {
    let j = i
    let temp = this[i]
    while (j > 0) {
      if (this[j - 1] > temp) {
        this[j] = this[j - 1]
      } else {
        break;
      }
      j--
    }
    this[j] = temp
  }
}

4.归并排序

Array.prototype.mergeSort = function () {
  const rec = (arr) => {
    if (arr.length === 1) { return arr }
    const middleIndex = Math.floor(arr.length / 2)
    const leftArr = arr.slice(0, middleIndex)
    const rightArr = arr.slice(middleIndex, arr.length)
    const orderLeft = rec(leftArr)
    const orderRight = rec(rightArr)
    const res = []
    while (orderLeft.length || orderRight.length) {
      if (orderLeft.length && orderRight.length) {
        res.push(orderLeft[0] < orderRight[0] ? orderLeft.shift() : orderRight.shift())
      } else if (orderLeft.length) {
        res.push(orderLeft.shift())
      } else if (orderRight.length) {
        res.push(orderRight.shift())
      }
    }
    return res
  }
  const res = rec(this)
  res.forEach((it, i) => this[i] = it)
}

5.快速排序

Array.prototype.quickSort = function () {
  const rec = (arr) => {
    if (arr.length <= 1) { return arr }
    const left = []
    const right = []
    const mid = arr[0]
    for (let i = 1; i < arr.length; i++) {
      if (arr[i] > mid) {
        right.push(arr[i])
      } else {
        left.push(arr[i])
      }
    }
    return [...rec(left), mid, ...rec(right)]
  }
  const res = rec(this)
  res.forEach((it, i) => this[i] = it)
}