Skip to content

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

@forrest-akin

Description

@forrest-akin

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
}

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type
    No fields configured for issues without a type.

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions