Can anyone please help me in understanding the following python code

Chris Angelico rosuav at gmail.com
Thu May 30 06:01:19 EDT 2013


On Thu, May 30, 2013 at 7:48 PM,  <bhk755 at gmail.com> wrote:
> Function mergeSort is called only once, but it is getting recursively executed after the printing the last statement "print("Merging ",alist)". But don't recursion taking place except at these places "mergeSort(lefthalf), mergeSort(righthalf)"
>
> Sometimes the function execution directly starts from i=0,j=0,k=0 . Not sure how.

When it says "Splitting" with a single-element list, it then
immediately prints "Merging" and returns (because all the rest of the
code is guarded by the 'if'). Execution then continues where it left
off, in the parent.

One good way to get an idea of what's going on is to add a recursion
depth parameter. Keep all the rest of the code the same, but change
the print and recursion lines to be like this:

def mergeSort(alist,depth):
    print("%*cSplitting %r"%(depth*2,' ',alist))
    # ...
        mergeSort(lefthalf,depth+1)
        mergeSort(righthalf,depth+1)
    # ...
    print("%*cMerging %r"%(depth*2,' ',alist))

mergeSort(alist,0)

That'll indent everything according to the depth of the call stack.
(Also, I changed your 'print's to be compatible with Python 2 and
Python 3; you seemed to have Python 3 style function calls and a
Python 2 interpreter.) Hopefully that'll make clearer what's going on!

ChrisA



More information about the Python-list mailing list