简体   繁体   English

为什么mergesort的这个python实现不起作用?

[英]Why doesn't this python implementation of mergesort work?

When I input [8,7,6,5,4,3,2,1] the output is => [4, 3, 2, 1, 8, 7, 6, 5] . 当我输入[8,7,6,5,4,3,2,1] ,输出为=> [8,7,6,5,4,3,2,1] [4, 3, 2, 1, 8, 7, 6, 5]

It seems like the only thing different from a working solution (comparing here ) is that instead of a sorted list, I have a k variable that I am incrementing, and update arr[k] in place of sorted . 似乎与工作解决方案( 在此处进行比较)唯一不同的是,我有一个要递增的k变量,而不是sorted列表,并用arr[k]代替了sorted

Why doesn't this work? 为什么不起作用? And how does updating arr[k] work? 以及如何更新arr[k] It seems like you would be losing data by updating the original input array. 似乎您将通过更新原始输入数组来丢失数据。

def mergesort(arr):
    if len(arr) == 1:
        return

    else:
        mid = len(arr)/2
        left = arr[0:mid]
        right = arr[mid:len(arr)]

        sorted = []
        i = 0
        j = 0
        mergesort(left)
        mergesort(right)

        while i < len(left) and j < len(right):
            if left[i] < right[j]:
                sorted.append(left[i])
                i += 1
            else:
                sorted.append(right[j])
                j += 1

        while i < len(left):
            sorted.append(left[i])
            i += 1

        while j < len(right):
            sorted.append(right[j])
            j += 1

        return sorted

You should just assign to left and right variable as you function return the sorted list after sorting also in the base case you should return a list and use // for integer division check this code 您应该只分配左右变量,因为函数在排序后返回排序后的列表,在基本情况下,您应该返回列表并使用//进行整数除法检查此代码

def mergesort(arr):
    if len(arr) == 1:
        return arr

    else:
        mid = len(arr)//2
        left = arr[0:mid]
        right = arr[mid:len(arr)]

        sorted = []
        i = 0
        j = 0
        left = mergesort(left) #left is now sorted
        right = mergesort(right)

        while i < len(left) and j < len(right):
            if left[i] < right[j]:
                sorted.append(left[i])
                i += 1
            else:
                sorted.append(right[j])
                j += 1

        while i < len(left):
            sorted.append(left[i])
            i += 1

        while j < len(right):
            sorted.append(right[j])
            j += 1

        return sorted

print (mergesort([8,7,6,5,4,3,2,1,3]))

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

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