Skip to content

冒泡排序

  1. 比较相邻的元素、如果前一个比后一个大,就交换
  2. 对每一位执行这个操作,这样一轮完成后会将最大的筛选出来放到最后
  3. 重复执行 1、2 步骤

js
Array.prototype.bubbleSort = function () {
  const arr = this;
  for (let i = 0; i < arr.length; i++) {
    for (let j = 0; j < arr.length - i - 1; j++) {
      if (arr[j] > arr[j + 1]) {
        const tmp = arr[j];
        arr[j] = arr[j + 1];
        arr[j + 1] = tmp;
      }
    }
  }
  console.log(arr);
};