Search code examples
javascriptsortingrecursionmergesort

Why does only a single statement gets printed in spite of 2 return statement in merge sort function?


I am trying to understand the recursion in merge sort. // merge sort

var arr = [1,5,3,0];

function mergeSort(arr) {
    if(arr.length == 1)
        return arr;

    if(arr.length > 1) {
        let breakpoint = Math.ceil((arr.length/2));
        // Left list starts with 0, breakpoint-1
        let leftList = arr.slice(0,breakpoint);
        // Right list starts with breakpoint, length-1
        let rightList = arr.slice(breakpoint,arr.length);

        // Make a recursive call
        leftList = mergeSort(leftList);
        rightList = mergeSort(rightList);

        var a = merge(leftList,rightList);
        return a;
    }
}

function merge(leftList,rightList) {
    let result = [];
    while(leftList.length && rightList.length) {
        if(leftList[0] <= rightList[0]) {
            result.push(leftList.shift());
        }else{
            result.push(rightList.shift());
        }
    }

    while(leftList.length)
        result.push(leftList.shift());

    while(rightList.length)
        result.push(rightList.shift());

    return result;
}

console.log(mergeSort(arr));

The program works fine, but I do not understand the recursion here. In spite of having multiple return statements, why does the program only print :

[0,1,3,5]

How does the result get printed, how the recursion is working here?


Solution

  • The program prints only once, because there is only one output statement in the entire logic flow: when mergeSort returns the final, sorted array to the main program, that result comes back as the value for the one and only console.log call.

    Remember that a return sends program control back to the spot that called that instance of the function. merge is called only from the bottom of mergeSort. However, mergeSort gets called from the main program and from two places within itself. For the given example, you will sometimes have three instances of mergeSort on the stack at the deepest point. The two higher ones will return to their call points within mergeSort; only the original will return to the main program's log command.