Dkyo Jeong
Dkyo Jeong

Reputation: 25

recursive merge sort in python

I am trying to make merge sort using two functions in python. But I got an error like
IndexError: list assignment index out of range whenever run my code. I don't know which part is wrong.
This is my code below. Any help will appreciate!!

def merge(A):

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

            temp=[]
            temp.append(99999)
            i=first
            j=mid+1
            k=0
            while i<=mid and j<=last:
                if A[i]<=A[j]:
                    temp[k]=A[i]
                    k=k+1
                    i=i+1
                else:
                    temp[k]=A[j]
                    k=k+1
                    j=j+1
            while i<=mid:
                temp[k]=A[i]
                k=k+1
                i=i+1
            while j<=last:
                temp[k]=A[j]
                k=k+1
                j=j+1
            a=0
            b=first
            while a<k:
                A[b]=temp[a]
                b=b+1
                a=a+1

    merge_sort(A,0,len(A)-1)

    return A

Upvotes: 0

Views: 738

Answers (1)

maij
maij

Reputation: 4218

You can not assign a value to temp[k] as long as this element does not exist.

Delete the row temp.append(99999), replace every temp[k]=A[i] by temp.append(A[i]) and every temp[k]=A[j] by temp.append(A[j]).

You will end up with:

def merge(A):

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

            temp=[]
            i=first
            j=mid+1
            k=0
            while i<=mid and j<=last:
                if A[i]<=A[j]:
                    temp.append(A[i])
                    k=k+1
                    i=i+1
                else:
                    temp.append(A[j])
                    k=k+1
                    j=j+1
            while i<=mid:
                temp.append(A[i])
                k=k+1
                i=i+1
            while j<=last:
                temp.append(A[j])
                k=k+1
                j=j+1
            a=0
            b=first
            while a<k:
                A[b]=temp[a]
                b=b+1
                a=a+1

    merge_sort(A,0,len(A)-1)

    return A


A = [1,9,4,5]
print(A)
print(merge(A))

Output:

[1, 9, 4, 5]
[1, 4, 5, 9]

Upvotes: 1

Related Questions