Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

冒泡排序如何实现,时间复杂度是多少, 还可以如何改进? #73

Open
meibin08 opened this issue Jan 13, 2020 · 2 comments

Comments

@meibin08
Copy link
Contributor

meibin08 commented Jan 13, 2020

@susouth
Copy link
Contributor

susouth commented Apr 9, 2020

  • 思路一:

冒泡排序:

function bubbleSort(arr) {
  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 temp = arr[j];
        arr[j] = arr[j + 1];
        arr[j + 1] = temp;
      }
    }
  }
  console.log(arr);
}

// 改进冒泡排序

function bubbleSort1(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);
}

@susouth
Copy link
Contributor

susouth commented Apr 9, 2020

  • 思路二:
function bubbleSort2(arr) {
  let low = 0;
  let high = arr.length - 1;
  let temp, j;

  while (low < high) {
    // 正排找最大
    for (j = low; j < high; ++j) {
      if (arr[j] > arr[j + 1]) {
        temp = arr[j];
        arr[j] = arr[j + 1];
        arr[j + 1] = temp;
      }
    }
    --high;

    // 反排找最小
    for (j = high; j > low; --j) {
      if (arr[j] < arr[j - 1]) {
        temp = arr[j];
        arr[j] = arr[j - 1];
        arr[j - 1] = temp;
      }
    }
    ++low;
  }
  console.log(arr);
}
  • 思路三?:

👇~~~~ 欢迎在下方评论补充你的答案,一起来学习~:pushpin:

扩展阅读:

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

2 participants