-1

I am trying to partition the list element recursively (like in divide and conquer) and consequently printing the sliced elements but suddenly sees unexpected abnormality(at line 6 and onwards in Output).

def Mergesort(a, l, r):
    if(l<r):
      mid = (r+l+1) // 2
      print(a)
      Mergesort(a[l : mid], l, mid-1)
      Mergesort(a[mid : r+1], mid, r)

a = [8, 3, -2, 6, 7, 4, 1, 2, -1, 0, 9, 12, 11, 5] 
Mergesort(a, 0, len(a)-1)

Output:

[8, 3, -2, 6, 7, 4, 1, 2, -1, 0, 9, 12, 11, 5]
[8, 3, -2, 6, 7, 4, 1]
[8, 3, -2]
[3, -2]
[6, 7, 4, 1]
[1]
[]
[2, -1, 0, 9, 12, 11, 5]
[]
[]
[]
[]
[]
Anurag
  • 37
  • 1
  • 6
  • 1
    What exactly was your expected output? – JvdV Mar 18 '20 at 12:21
  • [8, 3, -2, 6, 7, 4, 1, 2, -1, 0, 9, 12, 11, 5] [8, 3, -2, 6, 7, 4, 1] [8, 3, -2] [3, -2] [6, 7, 4, 1] [6, 7] [4, 1] [2, -1, 0, 9, 12, 11, 5] [2, -1, 0] [-1, 0] [9, 12, 11, 5] [9, 12] [11, 5] – Anurag Mar 18 '20 at 12:23

2 Answers2

0

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.

tianlinhe
  • 991
  • 1
  • 6
  • 15
0

I found the solution. Actually, while passing sliced list in function, index start from zero.

Anurag
  • 37
  • 1
  • 6