-1

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?

Koko
  • 131
  • 1
  • 10
  • Read this http://stackoverflow.com/questions/717725/understanding-recursion – san A Mar 27 '17 at 15:42
  • Your general question is something you should have already researched; you should have a specific question to ask about your lack of understanding. There are many explanations and illustrations of **mergeSort** on Stack Overflow and elsewhere on line. We expect that you've already gone through those. What *specifically* don't you understand? I've given you an answer below to address a couple of points you raised ... and voted to close the question, in case others agree with me. – Prune Mar 27 '17 at 16:51
  • No matter how many return statements there are in a function only one will get executed because return exits the function. Return does not mean print. It means stop running this function. – slebetman Mar 27 '17 at 23:39

1 Answers1

0

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.

Prune
  • 76,765
  • 14
  • 60
  • 81