JavaScript实现排序算法之冒泡排序

458 阅读1分钟

冒泡排序实现思路

冒泡排序算法相对其他排序运行效率较低,但是在概念上他是排序算法中最简单的

思路:

  1. 依次比较相邻的数字,如果前一个比后一个大,那么就交换。 即 小数放在前,大数放在后边。
  2. 然后比较第2个数和第3个数,小数在前,大数在后,依次类推则将最大的数滚动到最后边。
  3. 开始第二趟,将第二大的数移动至倒数第二位
  4. 依次类推.....

最后需要 第 (n-1) 趟就能完成排序。

参考动画: 冒泡排序动画

代码实现

class ArrayList {
  array = []
  // 用于插入数据
  insert(item) {
    this.array.push(item)
  }
  swap(m,n) {
    let temp = this.array[m]
    this.array[m] = this.array[n]
    this.array[n] = temp
  }

 // 冒泡排序  (核心代码在这里)
  bubblesSort() {
    if (this.array === null || this.array.length < 2) { return }
    // 这里注意需要 length -1 。 原因是 如果是最后一个数会有bug,因为没有 第最后一个数+1的数
    // 也可以理解将 length -1 为 比较的次数
    for (let j = this.array.length - 1; j >= 0; j--) {
      for (let i = 0; i < j; i++) {
        if (this.array[i] > this.array[i + 1]) {
          this.swap(i, i + 1)
        }
      }
    }
  }


let list = new ArrayList()
list.insert(12)
list.insert(2)
list.insert(45)
list.insert(123)
list.insert(481)
list.insert(56)
console.log(list.array);   // [ 12, 2, 45, 123, 481, 56 ]


// 调用冒泡排序
list.bubblesSort()
console.log(list.array);  // [ 2, 12, 45, 56, 123, 481 ]

冒泡排序的效率

冒泡排序的比较次数(假设每一次比较都需要交换):

  • 按照代码中来说,一共有6个数字
  • 第一次循环进行 6 次比较,第二次循环进行 5 次比较,第三次循环进行 4 次比较.....直到最后一趟进行一次比较
  • 对于 6 个数据来说就是: 6+5+4+3+2+1 次
  • 那么对于 n 个数据来就是: (n-1) + (n-2) + (n-3) + .....+ 1 = n * (n-1) / 2

通过大O表示法来推,则为 O(N²)

因为只考虑了每一次比较就需要交换, 所有大致的平均时间复杂度为: O(N²)