Doubt in merge sort debug with Javascript

1

I'm studying data structures with Javascript and so far everything was ok. But when I got into sorting algorithms, more specifically in merge sort, I ended up crashing, I can not understand the order of execution it follows. There's a double recursion, anyway, it's confusing for me. If anyone can help I thank you very much. Here is the code:

var mergeSortRec = function(array) {
    var length = array.length
    if(length === 1) {
        return array
    }
    var mid = Math.floor(length / 2),
    left = array.slice(0, mid),
    right = array.slice(mid, length)
    return merge(mergeSortRec(left), mergeSortRec(right))
}

var merge = function(left, right) {
    var result = [],
    il = 0,
    ir = 0

    while(il < left.length && ir < right.length) {
        if(left[il] < right[ir]) {
            result.push(left[il++])
        } else {
            result.push(right[ir++])
        }
    }

    while(il < left.length) {
        result.push(left[il++])
    }

    while(ir < right.length) {
        result.push(right[ir++])
    }

    return result
}

Suppose the inserted array is this: [6,2,5,2,4,5]

    
asked by anonymous 19.07.2018 / 03:11

0 answers