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

merge-sort-inplace.js is not In Place #39

Open
forrest-akin opened this issue Nov 29, 2016 · 0 comments
Open

merge-sort-inplace.js is not In Place #39

forrest-akin opened this issue Nov 29, 2016 · 0 comments

Comments

@forrest-akin
Copy link

forrest-akin commented Nov 29, 2016

merge-sort-inplace.js is not an example of an in place Merge Sort because arrays are being created and concatenated. Here's an example of an in place merge sort...

const mergeSort = (array, left = 0, right = array.length - 1) => {
    
    if (left >= right) return array

    let mid = Math.floor((left + right) / 2),
        i = mid + 1
    
    mergeSort(array, left, mid)
    mergeSort(array, i, right)

    while (left <= mid && i <= right) {
        if (array[left] < array[i]) left++
        else {
            array.splice(left, 0, array.splice(i, 1)[0])
            left++
            mid++
            i++
        }
    }

    return array
}
@forrest-akin forrest-akin changed the title merge-sort-inplace.js is not In merge-sort-inplace.js is not In Place Nov 29, 2016
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