pythonpython-3.xmergesort

MergeSort without merge function,, How does this algorithm merges the lists


def mergeSort(A):
    if len(A) < 2:
        return A

    mid = int(len(A)/2)
    left = mergeSort(A[:mid])
    right = mergeSort(A[mid:])

    r,l = 0,0
    B = []

    while len(B) < len(A):
        if r >= len(right) or (l < mid and left[l] < right[r]):
            B.append(left[l])
            l += 1
        elif r < len(right):
            B.append(right[r])
            r += 1

    return B

print(mergeSort([4,3,6,9,8,5,1]))

My doubt in the above program is how the lists are merged without a separate merge function?

After the recursive function calls in the end I think left and right lists contain only one element each... they are sorted and inserted in to list B using a while loop... what about other elements.. because here while loop is executed only once and how the list A is again split and merged...I got this program in internet and it works perfectly fine.


Solution

  • I think your problem is that you don't understand how recursion works. The while loop isn't only executed once, it's executed once per (non-trivial) recursive call.

    It's worth tracing through the operation. Whether you do it on paper, in the debugger, using a graphical visualizer like this one, or just by using a bunch of print calls, it's the only way you're really going to understand exactly what's going on.

    I think the graphical visualizer will be easier to follow, but learning how to do it on paper is worthwhile, so let's do that. We only need to step through one of the non-trivial merges, because after that they all look the same.

    As you can see, the while loop is actually executed six times, not just once.