简体   繁体   中英

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.

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 = mergesort(list_of_numbers)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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