Sunny-117 / js-challenges

✨✨✨ Challenge your JavaScript programming limits step by step

Home Page:https://juejin.cn/column/7244788137410560055

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

冒泡排序

Sunny-117 opened this issue · comments

冒泡排序
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]) {
        const temp = this[j + 1];
        this[j + 1] = this[j];
        this[j] = temp;
      }
    }
  }
}
// O(n^2), 冒泡排序
const arr = [6,5,4,3,2,1];
arr.bubbleSort();
const bubbleSort = function (arr: number[]): number[] {
  const len = arr.length;

  // 外层代表轮数,内层循环代表每轮要比较的次数
  for (let i = 0; i < len - 1; i++) {
    // flag作为一个标志位。可以优化冒泡排序,让算法的最好情况时间复杂度达到O(n)
    let flag = false;
    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]];
        flag = true;
      }
    }

    // 若一次交换也没发生,则说明数组有序,直接放过。
    if (!flag) return arr;
  }

  return arr;
};

// test
const arr = [5, 3, 2, 4, 1];
console.log(bubbleSort(arr));
  const arr = [7, 1, 3, 4, 5, 2, 6];
  function bubbleSort(array) {
    // 1.获取数组的长度
    let length = array.length;
    // 2.反向循环, 因此次数越来越少
    for (let i = length - 1; i >= 0; i--) {
      // 3.根据i的次数, 比较循环到i位置
      for (let j = 0; j < i; j++) {
        // 4.如果j位置比j+1位置的数据大, 那么就交换
        if (array[j] > array[j + 1]) {
          [array[j + 1], array[j]] = [array[j], array[j + 1]];
        }
      }
    }
    return arr;
  }
  console.log(bubbleSort(arr));
commented
//**:每轮都把最大的放到最后面
Array.prototype.myBubble = function () {
  for (let i = 0; i < this.length - 1; i++) {
    for (let j = 0; j < this.length - i - 1; j++) {
      if (this[j] > this[j + 1]) {
        [this[j], this[j + 1]] = [this[j + 1], this[j]];
      }
    }
  }
};
commented

sortFn([9, 32, 1, 34, 5, 3, 2, 67, 7])
function sortFn(arr) {
for (let i = 0; i < arr.length - 1; i++) {
for (let j = arr.length - 1; j > i; j--) {
if (arr[j] > arr[j - 1]) {
const temp = arr[j - 1]
arr[j - 1] = arr[j]
arr[j] = temp
}
}
}
}