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

插入排序 #60

Open
wl05 opened this issue Sep 21, 2019 · 0 comments
Open

插入排序 #60

wl05 opened this issue Sep 21, 2019 · 0 comments

Comments

@wl05
Copy link
Owner

wl05 commented Sep 21, 2019

插入排序:假设有一组待排序的数组arr = [10, 4, 5, 6, 1, 2, 3, 8, 7, 9, 10], 首先我们假设第一项已经排好了,紧接着我们选择第二项进行插入,当然我们要选择合适的位置,我们用当前项依次与前面已经排好的项进行比较,当找到比当前项小的位置时进行插入,以此类推。

function insertionSort(arr) {
    for (var i = 1, len = arr.length; i < len; i++) {
        var j = i
        var temp = arr[j]
        while (j > 0 && arr[j - 1] > temp) {
            arr[j] = arr[j - 1]
            j--
        }
        arr[j] = temp
    }
}

i 从1 开始,默认第一项(0位置)已经排好

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