Search code examples
pythonalgorithmsortingmergesortclrs

python merge sort issue


Not sure where I am going wrong with my implementation of merge sort in python.

import sys

sequence = [6, 5, 4, 3, 2, 1]

def merge_sort(A, first, last):
    if first < last:
        middle = (first + last) / 2
        merge_sort(A, first, middle)
        merge_sort(A, middle+1, last)
        merge(A, first, middle, last)

def merge(A, first, middle, last):
    L = A[first:middle]
    R = A[middle:last]

    L.append(sys.maxint)
    R.append(sys.maxint)

    i = 0
    j = 0
    for k in xrange(first, last):
        if L[i] <= R[j]:
            A[k] = L[i]
            i = i + 1
        else:
            A[k] = R[j]
            j = j + 1

merge_sort(sequence, 0, len(sequence))
print sequence

I would really appreciate it if someone could point out what is breaking my current implementation of merge sort.


Solution

  • The problem is here:

        merge_sort(A, first, middle)
        merge_sort(A, middle+1, last) # BEEP
    

    You only sort the second part from middle + 1, when you should start at middle. In fact, you never reorder the element at middle.

    Of course you cannot write either

        merge_sort(A, first, middle)
        merge_sort(A, middle, last) # BEEP, BEEP
    

    because when last = first + 1, you get middle == first and dive in an endless recursion (stopped by a RuntimeError: maximum recursion depth exceeded)

    So the way to go is:

        merge_sort(A, first, middle)
        if middle > first: merge_sort(A, middle, last)
    

    After that little change, your implementation gives correct results.