我尝试使用python实现合并排序算法,但代码不能很好地工作

这里合并函数:


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 listOfNumber


middle = 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]


临摹微笑
浏览 70回答 1
1回答

largeQ

您需要捕获在两半上运行的结果:merge_sort&nbsp; &nbsp; def merge_sort(lst):&nbsp; &nbsp; &nbsp; &nbsp; if len(lst) <= 1:&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; return lst&nbsp; &nbsp; &nbsp; &nbsp; middle = len(lst) // 2&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; left = merge_sort(lst[:middle])&nbsp; &nbsp; &nbsp; &nbsp; right = merge_sort(lst[middle:])&nbsp; &nbsp; &nbsp; &nbsp; return merge(left, right)您需要修改该函数,使其接受两个列表作为参数。merge
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Python