我没有得到排序列表,只有一个值。
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]))
答案 0 :(得分:1)
您没有解决左侧或右侧阵列中的任何一个耗尽的情况。您必须将其余值从非空数组复制到合并数组:
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]))