This is because your l, r
in def Mergesort
is not precise. When you Mergesort your RHS arraya=[2, -1, 0, 9, 12, 11, 5]
, it is actually running: Mergesort([2, -1, 0, 9, 12, 11, 5],7,10)
, but not Mergesort([2, -1, 0, 9, 12, 11, 5],0,3)
. Since len(a)=7, it will only return an empty array[]
.
I modified the codes:
def Mergesort(a, l, r):
if(l<r):
mid = (r+l+1) // 2
print (a)
#
Mergesort(a[l : mid], 0, len(a)-1)
Mergesort(a[mid : r+1],0, len(a)-1)
a = [8, 3, -2, 6, 7, 4, 1, 2, -1, 0, 9, 12, 11, 5]
Mergesort(a, 0, len(a)-1)
Now it can split both right and left arrays. Output if you print (a)
within if
clause:
[8, 3, -2, 6, 7, 4, 1, 2, -1, 0, 9, 12, 11, 5]
[8, 3, -2, 6, 7, 4, 1]
[8, 3, -2, 6, 7, 4, 1]
[8, 3, -2]
[8, 3, -2]
[8]
[3, -2]
[3]
[-2]
[]
[6, 7, 4, 1]
[6, 7, 4]
[6, 7]
[6]
[7]
[4]
[1]
[]
[2, -1, 0, 9, 12, 11, 5]
[2, -1, 0, 9, 12, 11, 5]
[2, -1, 0]
[2, -1, 0]
[2]
[-1, 0]
[-1]
[0]
[]
[9, 12, 11, 5]
[9, 12, 11]
[9, 12]
[9]
[12]
[11]
[5]
[]
Notice that is code is still not perfect and needs work (but it solves the splitting issue that you raised), I would suggest improvements in
1) definition of mid
so it correctly split even-number array;
2) definition of l
and r
so that it would not split single-element array.