Search code examples
pythonmergesortclrs

Why won't this merge sort implementation work?


I am following along with the CLRS book and am implementing all the algorithms in python as I go along, this is the merge sort algorithm. I tested the merge function on a test array and it works, so it must be the merge_sort function, however it's pretty much the same as the pseudocode in the book.

def merge_sort(self, array, p, r):
    if p < r:
        q = int((p + r) / 2)

        self.merge_sort(array, p, q)
        self.merge_sort(array, q + 1, r)
        self.merge(array, p, q , r)

def merge(self, array, p, q, r):
    n1 = q - p + 1
    n2 = r - q
    left = []
    right = []

    for i in range(0, n1):
        left.append(array[p + i])

    for j in range (0, n2):
        right.append(array[q + j + 1])

    left.append(math.inf)
    right.append(math.inf)
    i = 0
    j = 0

    for k in range(p, r):
        if left[i] <= right[j]:
            array[k] = left[i]
            i += 1
        else:
            array[k] = right[j]
            j += 1

Solution

  • I'm going to guess that this:

    for k in range(p, r):
    

    should be:

    for k in range(p, r + 1):
    

    This will make k take on all values from p to r, before it was taking on the values of p to r - 1 -- just the way range() works.