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

基础算法:冒泡排序 #5

Open
cj0x39e opened this issue Sep 12, 2019 · 1 comment
Open

基础算法:冒泡排序 #5

cj0x39e opened this issue Sep 12, 2019 · 1 comment

Comments

@cj0x39e
Copy link
Contributor

cj0x39e commented Sep 12, 2019

问题

给定下面的数组,请使用 冒泡排序 算法使其按从小到大的顺序排列?

const list = [1, 7, 9, 8, 3, 2, 10];

...🤔
...🤔
...🤔
...🤔
...🤔
...🤔
...🤔
...🤔
...🤔
...🤔
...🤔
...🤔
...🤔
...🤔
...🤔
...🤔

丰橙解答

/**
 * 冒泡排序
 * @param {Array} list 待排序数组
 */
function bubbleSort(list) {

    // 每次比较两个数字
    // 如果他们的顺序不是按从小到大排列就交换
    // 直到遍历完成
    for (let i = 0; i < list.length - 1; i++) {
        for (let j = 0; j < list.length - 1 - i; j++) {
            if (list[j] > list[j + 1]) {
                const temp = list[j];
                list[j] = list[j + 1];
                list[j + 1] = temp;
            }
        }
    }

    return list;
}

// test
const list = [1, 7, 9, 8, 3, 2, 10];
console.log(bubbleSort(list)); // [ 1, 2, 3, 7, 8, 9, 10 ]

时间复杂度

O(log n x n)

可视化链接

https://algorithm-visualizer.org/brute-force/bubble-sort

测试链接

因为 leetcode 测试用例很多,所以在 leetcode 测试通过就行了:
https://leetcode-cn.com/problems/sort-an-array/

@guxinduyin666
Copy link

function bubbleSort(list){
     const len=list.length;
            for(let i=0;i<len;i++){
                for(let j=i+1;j<len;j++){
                    if(list[j]<list[i]){
                        [list[i],list[j]]=[list[j],list[i]]
                    }
                }
            }
            return list;
 }       

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

2 participants