簡體   English   中英

在Python中執行合並合並排序時出現錯誤

[英]Errors arises when implement merge sort in python

我正在嘗試在python中實現合並排序,如下所示:

def MergeSortTopdown(list_n):
     #Base condition to stop recursion
    if len(list_n) == 1:
        return list_n
    else:
        mid = int(len(list_n)/2)
        first_half = list_n[:mid]
        second_half = list_n[mid:]
        MergeSortTopdown(first_half)
        MergeSortTopdown(second_half)
        i = 0
        j = 0 
        n = len(list_n)
        for k in range(n):
            if j >= len(first_half) and i < len(second_half):
                list_n[k] = first_half[i]
                i += 1 
            if i >= len(first_half) and j < len(second_half): 
                list_n[k] = second_half[j]
                j += 1
            if i < len(first_half) and j < len(second_half):
                if first_half[i] > second_half[j]:
                    list_n[k] = second_half[j]
                    j += 1   
                elif second_half[j] > first_half[i]:
                    list_n[k] = first_half[i]
                    i += 1
                elif second_half[i] == first_half[j]:
                    list_n[k] = first_half[i]
                    if i>j:
                        i += 1
                    else:
                        j += 1

    return list_n

當我測試已經排序的列表時,這似乎是合理的。 但是,當我運行時,此錯誤引發:

MergeSortTopdown([3,4,6,7,1,8,56,112,67])
Traceback (most recent call last):

  File "<ipython-input-11-29db640f4fc6>", line 1, in <module>
    MergeSortTopdown([3,4,6,7,1,8,56,112,67])

  File "C:/Users/Emmanuel Hoang/MergeSortTopDown.py", line 13, in MergeSortTopdown
    MergeSortTopdown(second_half)

  File "C:/Users/Emmanuel Hoang/MergeSortTopDown.py", line 13, in MergeSortTopdown
    MergeSortTopdown(second_half)

  File "C:/Users/Emmanuel Hoang/MergeSortTopDown.py", line 19, in MergeSortTopdown
    list_n[k] = first_half[i]

IndexError: list index out of range

您能告訴我我的代碼有什么問題嗎,有什么方法可以改善我的代碼。 先感謝您

您試圖引用列表末尾的元素。 我在代碼中添加了一些簡單的print語句:

   for k in range(n):
        print("LOOP TOP", k, first_half, second_half, list_n)
        if j >= len(first_half) and i < len(second_half):
            print("TRACE", list_n, k, "\t", first_half, i)
            list_n[k] = first_half[i]
            i += 1

然后,我將輸入列表縮短為[8,56,112,3,67]

輸出:

LOOP TOP 0 [8] [56] [8, 56]
LOOP TOP 1 [8] [56] [8, 56]
LOOP TOP 0 [3] [67] [3, 67]
LOOP TOP 1 [3] [67] [3, 67]
LOOP TOP 0 [112] [3, 67] [112, 3, 67]
LOOP TOP 1 [112] [3, 67] [3, 3, 67]
TRACE [3, 3, 67] 1   [112] 0
LOOP TOP 2 [112] [3, 67] [3, 67, 67]
TRACE [3, 67, 67] 2      [112] 1

其次是您崩潰。 當只有元素0時,您嘗試獲取first_half[1]

分析

您具有三個連續的if語句來檢查列表范圍:

        if j >= len(first_half) and i < len(second_half):
        if i >= len(first_half) and j < len(second_half): 
        if i < len(first_half) and j < len(second_half):

您在第一個檢查中切換了ijifirst_half下標。 此更改修復了合並:

        if i < len(first_half) and j >= len(second_half):

建議

問題的部分原因是合並邏輯太復雜。 在循環的主要部分中,您需要進行一次值檢查:將列表標題的下半部分移到合並列表中。 當兩個索引都在范圍內時執行此操作。

然后,當一個索引到達其列表的末尾時,退出循環並添加另一列表的其余元素。 使用extend方法。 所以...

while i < len(first_half) and j < len(second_half):
    if first_half[i] < second_half[j]:
        # move smaller element to list_n;
        # increment i or j as needed
    k += 1

# One of these will be an empty operation.
list_n.extend(first_half[i:])
list_n.extend(second_half[j:])

解決IndexError

如果你已經合並列表中的所有元素-你在合並排序的你“的合並操作”檢查第一種情況second_half -有你的兩個列表的名稱first_halfsecond_half切換左右。 代替這個:

if j >= len(first_half) and i < len(second_half):
    list_n[k] = first_half[i]
    i += 1 

你應該有這個:

if j >= len(second_half) and i < len(first_half):
    list_n[k] = first_half[i]
    i += 1

這將正確檢查上面指定的條件。

為什么會這樣:

之所以收到IndexError是因為您試圖調用first_half[i]並且在執行此操作之前未正確確認ifirst_half列表中的有效索引。

暫無
暫無

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

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