Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

python merge sort issue [closed]

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.

like image 423
nuce Avatar asked Jan 26 '16 12:01

nuce


2 Answers

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.

like image 93
Serge Ballesta Avatar answered Oct 19 '22 03:10

Serge Ballesta


There are 2 errors in the code:

  • if first < last: should be if first < last and last-first >= 2:
  • merge_sort(A, middle+1, last) should be merge_sort(A, middle, last)
like image 30
Anmol Singh Jaggi Avatar answered Oct 19 '22 02:10

Anmol Singh Jaggi