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

排序算法 #27

Closed
NuoHui opened this issue Jan 22, 2020 · 1 comment
Closed

排序算法 #27

NuoHui opened this issue Jan 22, 2020 · 1 comment

Comments

@NuoHui
Copy link
Owner

NuoHui commented Jan 22, 2020

function bubbleSort(list) {
    if (Array.isArray(list)) {
        if (list.length <= 1) return list;
        // 外层循环控制总的遍历轮数,理论上等于数组长度
        for(let i = 0; i < list.length; i++) {
            // j才是真正对比数据的轮,- i是因为需要排除之前每轮对比出来的数
            let flag = false // 标示是否有数据发生交换
            for(let j = 0; j < list.length - 1 - i; j++) {
                if (list[j + 1] < list[j]) {
                    const temp = list[j];
                    list[j] = list[j + 1];
                    list[j + 1] = temp;    
                    flag = true;
                }
            }
            // 没有数据发生交换说明已排序完成
            if (!flag) {
                break
            }
        }
    }
    return list;
}
@NuoHui
Copy link
Owner Author

NuoHui commented Jan 22, 2020

function insertionSort(list) {
    if(Array.isArray(list)) {
        if (list.length <= 1) return list
        // i表示未排序区间
        for(let i = 1; i < list.length; i++) {
            // 待对比元素
            const value = list[i]
            let j = i - 1
            // j表示已排序区间
            for(; j >= 0; j--) {
                // 这里选择从已排序末尾插入不是从开头
                if(list[j] > value) {
                    list[j + 1] = list[j] // 交换位置
                } else {
                    // 如果已排序的最大元素都小于或者等于待对比元素直接跳出
                    break
                }
            }
            list[j + 1] = value // 插入元素
        }
    }    
    return list
}

@NuoHui NuoHui changed the title 备注下 排序算法 Jan 22, 2020
@NuoHui NuoHui closed this as completed Mar 16, 2020
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