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

99.冒泡排序 #99

Open
webVueBlog opened this issue Mar 3, 2023 · 0 comments
Open

99.冒泡排序 #99

webVueBlog opened this issue Mar 3, 2023 · 0 comments

Comments

@webVueBlog
Copy link
Member

// 原理
// 从左往右,相邻元素进行比较,如果前一个元素大于后一个元素,则交换
// 这样全部遍历完成,最大的数会在最右边冒泡出来
// 时间复杂度: 最好时间复杂度 O(n),平均时间复杂度 O(n^2)
// 空间复杂度 O(1)
// 在相邻元素相等时,它们并不会交换位置,所以,冒泡排序是稳定排序。
// 冒泡排序思路简单,代码也简单,特别适合小数据的排序。但是,由于算法复杂度较高,在数据量大的时候不适合使用。
/**
 * 冒泡排序
 * @param {*} arr
 */

function bobbleSort(arr) {
 for (let i = 0; i < arr.length; i++) {
  for (let j = 0; j < arr.length - i - 1; j++) {
    // 判断
    if (arr[i] > arr[j+1]) {
     const temp = arr[j];
     arr[j] = arr[j+1];
     arr[j+1] = temp;
    }
  }
 }
} 
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant