Merge Sort not happening correctly - Python
<p>Sorting is not happening correctly. Can some one help on sorting with this approach. Also please let me know where I am going wrong. I am new to Python so I am doing this myself. I am using the usual approach as we do in C or other languages.</p>

<pre><code>base =[5,4,3,2,1]

def splitarray (low, high):
    if  low &lt; high:
        mid = (high+low)/2

        splitarray (low, mid)
        splitarray (mid+1,high)
        merge(low,mid,high)

    else:
        return

def merge(low,mid,high):
    print("merge " +str(low) + " - " +str(mid)+" - "+ str(high))
    result = [0]*len(base)
    k = 0
    i=low
    j=mid+1
    l=0


    while i &lt;= mid and j &lt;= high:
        if (base[i] &lt; base[j]):

            result[k]= base[i]
            k+=1
            i += 1

        if (base[i] &gt; base[j])  :


            result[k]= base[j]

            j += 1
            k += 1





    while i &lt;= mid:
        result[k]= base[i]
        k += 1
        i += 1
    while j &lt;= high:
        result[k]= base[j]
        #count = count + mid - i
        j += 1
        k += 1

    print result

    l = low
    k= 0
    while l &lt;= high:
        base[l] = result[l]
        l += 1


    print base
splitarray(0,len(base)-1)
</code></pre>

<p>The issue with your current (updated) code appears to be with the last loop:</p>

<pre><code>l = low
k= 0
while l &lt;= high:
    base[l] = result[l]
    l += 1
</code></pre>

<p>Here you're copying the values from the <code>results</code> list to the <code>base</code> list. However, the results are all at the start of <code>results</code>, not at the same coordinates you want them to go in <code>base</code>. You seem to have <em>almost</em> got it right since you're setting <code>k</code> to zero, but you don't end up using <code>k</code> in the loop.</p>

<p>Try:</p>

<pre><code>l = low
k= 0
while l &lt;= high:
    base[l] = result[k]  # read the result from index k, not l
    l += 1
    k += 1  # increment k as well
</code></pre>

<p>This should work as intended. Note that while this will do the sorting correctly, this isn't a very elegant way of sorting in Python. To start with, you can only sort the one global variable <code>base</code>, not any list (it would be much nicer to pass the list as a parameter). However, since this looks like something you've written mostly for the learning experience, I'll leave further improvements up to you.</p>

python mergesort