On Thu, May 30, 2013 at 7:48 PM,  <bhk...@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
-- 
http://mail.python.org/mailman/listinfo/python-list

Reply via email to