簡體   English   中英

在 python 中實現歸並排序

[英]Implementing merge-sort in python

我正在嘗試在 Python 3 中實現合並排序算法。這是實現算法合並部分的 function:

def Merge(A,p,q,r):
n1 = q - p + 1
n2 = r - q

#We first populate two lists that contain the sorted subsequences A[p,...,q] and A[q+1,...,r]
L = []
R = []

for index in range(n1):
    L.append(A[index + p])

for index in range(n2):
    R.append(A[index + q + 1])

#We now overwrite the A[p,..,q,...r] section of the list by comparing the 'top-most'
#elements in the lists l and R and putting the smaller element in the corresponding
#entry in A. If one of the list is fully exposed/no longer available, we simply put the 
#remaining list's elements in the corresponding positions in A.

i = 0
j = 0

for k in range(r - p + 1 ):

    if i > n1-1:
        A[k] = R[j]
        j = j + 1

    elif j > n2-1:
        A[k] = L[i]
        i = i + 1

    elif L[i] < R[j]:
        A[k] = L[i]
        i = i + 1

    else:
        A[k] = R[j]
        j = j + 1 

return A   

我已經測試了這個 function 並且它運行良好:只要對子數組 A[p,q] 和 A[q+1,r] 進行排序,整個數組 A[p,r] 就會正確排序。 我現在嘗試實施一種分而治之的方法來合並足夠大的列表。

import math

def Merge_Sort(A,p,r):

if p == r:

    return A

if p < r:

    q = math.floor((p+r)/2)
    Merge_Sort(A,p,q)
    Merge_Sort(A,q+1,r)
    Merged_List = Merge(A,p,q,r)

return Merged_List

但是當我運行它時,我得到了錯誤的答案。 這是一個例子:

#We now analyze the merge sort algorithm.
A = [1,7,9,3]
B = Merge_Sort(A,0,3)
print(B)

output 是

[3, 9, 3, 9]

我可能在實現分而治之時犯了一些明顯/愚蠢的錯誤。 建議?

錯誤出在對A[k]的分配中。 它們應該更改為對A[p+k]的分配。

請注意, LR可以使用以下語法定義(無顯式循環):

L = A[p:q+1]
R = A[q+1:r+1]

為了與本機函數在 Python(例如list.extend )中的工作方式保持一致,您的兩個函數不應返回列表。 它們會改變您作為參數傳遞的列表,因此為避免混淆,最好不要返回它:它可能會使您的代碼用戶認為 function 沒有副作用。

在合並排序算法中,我們首先將數組遞歸地分成兩部分,然后對每一部分進行排序並遞歸合並。所以,它是一種分治算法。

MergeSort(arr[], l,  r)
If r > l
     1. Find the middle point to divide the array into two halves:  
             middle m = (l+r)/2
     2. Call mergeSort for first half:   
             Call mergeSort(arr, l, m)
     3. Call mergeSort for second half:
             Call mergeSort(arr, m+1, r)
     4. Merge the two halves sorted in step 2 and 3:
             Call merge(arr, l, m, r)

我認為您的代碼在合並 function 中存在問題。您應該在哪里分配數組 L 和數組 R 的元素。 您的起始索引是 p,因此您應該將 L[i] 和 R[i] 分配給 A[p+k] 而不是 A[k]。 如果您對歸並排序仍有疑問,請參閱歸並排序 希望這能解決您的所有疑問。 謝謝

暫無
暫無

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

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