一些必须会的常见排序(一)

公众号: 手摸手前端进阶

1、冒泡排序
/**
 * 比较所有相邻的元素,如意第一个比第二个大,则交换它们
 * 一轮下来,可以保证最后一个数是最大的
 * 执行 n-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]) {
        [this[j], this[j + 1]] = [this[j + 1], this[j]]
      }
    }
  }
}

const arr = [5, 4, 3, 3, 32, 1]
arr.bubbleSort()

// 时间复杂度:O(n^2)
// 但是冒泡排序性能很差,基本上在工作中很少用到,大多还是在面试中出现
复制代码
2、选择排序
/** 
 * 找到数组中的最小值,选中它并将其将其放置在第一位
 * 接着找到第二小的值,选中它并将其放置在第二位
 * 以此类推,执行 n-1 轮
 */
Array.prototype.selectionSort = function () {
  for (let i = 0; i < this.length - 1; i++) {
    let indexMin = i
    for (let j = i; j < this.length; j++) {
      if (this[j] < this[indexMin]) {
        indexMin = j
      }
    }
    if (indexMin !== i) {
      [this[i], this[indexMin]] = [this[indexMin], this[i]]
    }
  }
}
const arr1 = [5, 4, 3, 3, 32, 1]
arr1.selectionSort()
// 两个嵌套循环,时间复杂度:O(n^2)
// 选择排序同冒泡排序一样性能很差,基本上在工作中很少用到,大多还是在面试中出现
复制代码
3、插入排序
/** 
 * 从第二个数开始往前比
 * 比它大的就往后排
 * 以此类推进行到最后一个数
 */

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

const arr2 = [5, 4, 3, 3, 32, 1]
arr2.insertionSort()

// 两个嵌套循环,时间复杂度:O(n^2)
复制代码
© 版权声明
THE END
喜欢就支持一下吧
点赞0 分享