Reputation: 71
I didn't get the sorted list, instead only one value.
def merge1(left,right):
print("left" , left , "right" , right)
def loop(left,right,ss):
print("left" , left , "right" , right)
if not (left ==[] or right ==[]):
if left[0] <= right[0]:
ss.append(left[0])
return loop(left[1:],right, ss)
else:
ss.append(right[0])
return loop(left,right[1:], ss)
print("hello")
else:
return ss
return loop(left,right,[])
def msort(s):
if len(s)>1:
mid = len(s) // 2
return merge1(msort(s[:mid]),msort(s[mid:]))
else:
return s
print(msort([9,8,7,6,5,4,3,2,1]))
Upvotes: 0
Views: 174
Reputation: 1916
You are not addressing the case where either one of the left or right array is exhausted. You will have to copy the remaining values from the non-empty array to the merged array:
def merge1(left,right):
print("left" , left , "right" , right)
def loop(left,right,ss):
print("left" , left , "right" , right)
if left and right:
if left[0] <= right[0]:
ss.append(left[0])
return loop(left[1:],right, ss)
else:
ss.append(right[0])
return loop(left,right[1:], ss)
# either one of left or right is empty so you need to copy the remaining
# values into merged array
else:
if left:
for i in left:
ss.append(i)
if right:
for i in right:
ss.append(i)
print ss
return ss
return loop(left,right,[])
def msort(s):
if len(s)>1:
mid = len(s) / 2
return merge1(msort(s[:mid]),msort(s[mid:]))
else:
return s
print(msort([9,8,7,6,5,4,3,2,1]))
Upvotes: 1