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

为什么插入排序比冒泡排序更受欢迎? #3

Open
CodeRookie262 opened this issue Dec 18, 2020 · 0 comments
Open

为什么插入排序比冒泡排序更受欢迎? #3

CodeRookie262 opened this issue Dec 18, 2020 · 0 comments

Comments

@CodeRookie262
Copy link
Owner

CodeRookie262 commented Dec 18, 2020

插入排序和冒泡排序的空间,时间复杂度都一样,也是属于原地排序的稳定排序算法,为何插入排序比冒泡排序更受欢迎?

对于排序算法的执行效率主要可以通过以下3方面解析:

  1. 最好,最坏,平均情况时间复杂度;
  2. 时间复杂度的系数,常熟和阶数;
  3. 比较,交换(移动)的次数;

可以看看插入排序与冒泡排序的元素交换区别:

插入排序

if (array[j] > value) {
  array[j + 1] = array[j];
} else {
  // 因为左边是排序区间,如果与最后的元素已经处于有序的话则说明该元素不用在单轮循环与其他元素进行排序了。
  break;
}

冒泡排序

 if (arr[j] > arr[j + 1]) {
  isChange = true;
  // Core code
  let  tmp = arr[i];
  arr[i] = arr[j];
  arr[j] = tmp;
  // [arr[j], arr[j + 1]] = [arr[j + 1], arr[j]]; ES 新语法,同上效果一致
}

可以明显看出冒泡排序的元素交换次数是排序排序的3倍交换次数,假设在对 K 哥元素进行排序,每次交换操作耗时单位为 ut,那么冒泡排序在交换元素上就是 3K * ut,而插入则是 K * ut。

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

1 participant