冒泡排序以及其改进

let array = [8, 3, 0, 32, 99, 1, 888, 23, 6, 5, 999, 1, 342, 3, 6, 23, 55]

function bubbleSort(array) {
  for (let i = 0; i < array.length - 1; i++) {
    for (let j = 0; j < array.length - 1 - i; j++){
      if (array[j] > array[j + 1]) {
        let tmp = array[j + 1]
        array[j + 1] = array[j]
        array[j] = tmp
      }
    }
  }
  console.log("array", array)
}

// 改进冒泡排序1
function bubbleSortNice(array) {
  let pos = 0;
  let length = array.length - 1
  for (let i = 0; i < array.length - 1; i++) {
    for (let j = 0; j < length; j++){
      if (array[j] > array[j + 1]) {
        let tmp = array[j + 1]
        array[j + 1] = array[j]
        array[j] = tmp
        pos = j
      }
    }
    length = pos
  }
  console.log("array", array)
}

// 改进冒泡排序2
function bubbleSortNice2(arr) {
    let i = arr.length - 1;
    while (i > 0) {
        let pos = 0;
        for (let j = 0; j < i; j++) {
            if (arr[j] > arr[j + 1]) {
                pos = j;
                const temp = arr[j];
                arr[j] = arr[j + 1];
                arr[j + 1] = temp;
            }
        }
        i = pos;
    }
    console.log(arr);
}

console.time("bubbleSort")
bubbleSort(array)
console.timeEnd("bubbleSort")

console.time("bubbleSortNice")
bubbleSortNice(array)
console.timeEnd("bubbleSortNice")

console.time("bubbleSortNice2")
bubbleSortNice2(array)
console.timeEnd("bubbleSortNice2")
6874013-a33ef37b582feee5.jpg
运行时间

猜你喜欢

转载自blog.csdn.net/weixin_34041003/article/details/90885907