这里合并函数:def __merge__(arr, middle): L = arr[:middle] R = arr[middle:] L.append(math.inf) R.append(math.inf) i = 0 j = 0 for k in range(0, len(arr)): if(L[i] <= R[j]): arr[k] = L[i] i += 1 else: arr[k] = R[j] j += 1 return arr这里合并排序函数,以递归方式调用 intself:def __mergeSort__(listOfNumber):if(len(listOfNumber) <= 1): return listOfNumbermiddle = int( len(listOfNumber) / 2 )print('merge lit: ', listOfNumber[:middle])__mergeSort__(listOfNumber[:middle])print('merge lit: ', listOfNumber[middle:])__mergeSort__(listOfNumber[middle:])print(__merge__(listOfNumber, middle))return __merge__(listOfNumber, middle)当我给出像[6,5,4,3,2,1]这样的数组作为输入时,我得到这个:[3,2,1,6,5,4]
1 回答
largeQ
TA贡献2039条经验 获得超7个赞
您需要捕获在两半上运行的结果:merge_sort
def merge_sort(lst):
if len(lst) <= 1:
return lst
middle = len(lst) // 2
left = merge_sort(lst[:middle])
right = merge_sort(lst[middle:])
return merge(left, right)
您需要修改该函数,使其接受两个列表作为参数。merge
添加回答
举报
0/150
提交
取消