簡體   English   中英

合並python中的排序實現給出錯誤的結果

[英]Merge sort implementation in python giving incorrect result

我正在嘗試實現Jeff Erickson在第3頁的這些注釋中描述的合並排序算法,但是即使該算法是正確的並且我的實現似乎是正確的,我也將輸入列表作為輸出而沒有任何更改。 有人可以指出其中的異常嗎?

def merge(appnd_lst, m):
    result = []
    n = len(appnd_lst)
    i, j = 0, m
    for k in range(0, n):
        if j < n:
            result.append(appnd_lst[i])
            i += 1
        elif i > m:
            result.append(appnd_lst[j])
            j += 1
        elif appnd_lst[i] < appnd_lst[j]:
            result.append(appnd_lst[i])
            i += 1
        else:
            result.append(appnd_lst[j])
            j += 1

    return result


def mergesort(lst):
    n = len(lst)
    if n > 1:
        m = int(n / 2)
        left = mergesort(lst[:m])
        right = mergesort(lst[m:])

        appnd_lst = left
        appnd_lst.extend(right)
        return merge(appnd_lst, m)
    else:
        return lst


if __name__ == "__main__":
    print mergesort([3, 4, 8, 0, 6, 7, 4, 2, 1, 9, 4, 5])

您的合並功能中存在三個錯誤,幾個索引錯誤以及使用了錯誤的比較運算符。 請記住,python列表索引從0開始。len(list)-1。

* ...
6        if j > n-1:  # operator wrong and off by 1
* ...
9        elif i > m-1: # off by 1
* ...

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM