Search code examples
javascriptsortingrecursionmergesortmutual-recursion

Does this implementation of merge sort use mutual recursion?


Does this mergeSort algorithm use mutual recursion? I realize that mergeSort calls the merge function and it calls itself (mergeSort), but since merge does not call mergeSort is it not mutual recursion and simply just recursion?

function mergeSort(arr) {
    // split array
    ...
    return merge(mergSort(firstHalf), mergeSort(secondHalf));
}

function merge (array1, array2) {
    // merge both arrays
    ...
    return singleArray;
}

Solution

  • Correct: this is simple recursion. Mutual recursion is also called indirect recursion: A calls B; B calls A.

    Your analysis is exactly correct: were merge to call mergeSort, then you would have mutual recursion. In the posted code, the call to merge is a simple parent-child link on the call tree.