singam suresh
singam suresh

Reputation: 45

While working with merge sort im getting recursion error

def MergeSort(arr,l,r):
if l>=r:
    return 
mid=(l+r)//2
MergeSort(arr,l,mid+1)
MergeSort(arr,mid+1,r)
Merge(arr,l,r,mid)

def Merge(arr,l,r,mid):

a=arr[l:mid+1] #left subarray
b=arr[mid+1:r+1] #right sub array

i=0 #left sub array index
j=0 #right sub array index
k=i #sorted array index

while i<len(a) and j<len(b):
    if(a[i]<=b[j]):
        arr[k]=a[i]
        i=i+1
    else:
        arr[k]=b[j]
        j=j+1
    k=k+1
while i <len(a):
    arr[k]=a[i]
    i=i+1
    k=k+1
while j<len(b):
    arr[k]=b[j]
    j=j+1
    k=k+1

arr=[38, 27, 43, 3, 9, 82, 10,2] MergeSort(arr,0,len(arr)-1) print(arr)

this code is giving me error i'm not able to figure it out.

THE ERROR IS:

MergeSort.py", line 38, in MergeSort(arr,0,len(arr)-1)

MergeSort.py", line 7, in MergeSort MergeSort(arr,l,mid+1)

sort\MergeSort.py", line 4, in MergeSort if l>=r: RecursionError: maximum recursion depth exceeded in comparison

Upvotes: 0

Views: 63

Answers (1)

Asad Awadia
Asad Awadia

Reputation: 1521

The first recursive call goes from left to mid not mid + 1

Upvotes: 0

Related Questions