简体   繁体   English

在Python中合并排序问题

[英]Merge Sort Problems In Python

So I'm trying to teach myself how to write a merge sort but for whatever reason I can't seem to make it work. 所以我试着教自己如何编写合并排序,但无论出于何种原因,我似乎无法使其工作。

    def merge(left, right):
        result = []
        i ,j = 0, 0
        while i < len(left) and j < len(right):
            if left[i] <= right[j]:
                result.append(left[i])
                i += 1
            else:
                result.append(right[j])
                j += 1
        result += left[i:]
        result += right[j:]
        return result

    def mergesort(numlist):
        if len(numlist) < 2:
            return numlist
        middle = int(len(numlist)/2)
        left = mergesort(numlist[:middle])
        right = mergesort(numlist[middle:])
        return merge(left, right)

Every list I feed into the sort then attempt to print just comes up the exact same with no changes 我提供给排序的每个列表然后尝试打印只是完全相同而没有任何变化

Answering so this can be closed though it was fixed in comments with the help of @Jean-François Fabre. 回答这个问题可以在@ Jean-FrançoisFabre的帮助下在评论中修复。

Your current code works fine but it does not sort the list in-place. 您当前的代码工作正常,但它不会就此对列表进行排序。 In the case of sorting a list called list_of_numbers , you need to assign the result back to list_of_numbers : 在排序名为list_of_numbers的列表的情况下,您需要将结果分配回list_of_numbers

list_of_numbers = mergesort(list_of_numbers)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM