为什么此合并排序无法正常工作?

时间:2020-10-12 07:56:43

标签: python python-3.x algorithm sorting mergesort

我需要使用Python 3实现合并排序。我对其进行了编码。但是它没有给出正确的输出。有人可以检查吗? 这是我的代码,

def mergeSort(A, p, r): 
    if p < r:
        q = (p + r) // 2
        mergeSort(A, p, q)
        mergeSort(A, q+1, r)
        Merge(A, p, q, r)

def Merge(A, p, q, r):
    i = 1
    j = q+1
    k = 0
    TEMP = [0] * (r+1)

    while i <= q and j <= r:
        if A[i] <= A[j]:
            TEMP[k] = A[i]
            k += 1
            i += 1
        else:  
            TEMP[k] = A[j] 
            k += 1
            j += 1
    if (j > r) :
        for t in range(0, q-1):
            A[r-t] = A[q-t]

    for t in range(0, k-1):
       A[p+t] = TEMP[t+1]

A = [15, 16, 13, 10, 19, 18]
mergeSort(A, 0, len(A)-1)
print(A)

谢谢

2 个答案:

答案 0 :(得分:1)

(对我而言)执行合并的方式看起来很奇怪,但我会纠正目前为止的情况。

1- i的初始化值是错误的,应该是:

i = p

因为我是您要在数组A中查找的第一个元素。

2- TEMP数组大小的初始化值错误,应为:

(r - p + 1)

3-填写TEMP数组和/或替换A数组元素似乎是一个错误,这是固定的代码。在第一个while循环之后,我对零件进行了评论,以指示此时需要执行的操作。

def mergeSort(A,p,r): 
    if p < r:
        q = (p+r)//2
        mergeSort(A,p,q)
        mergeSort(A,q+1,r)
        Merge(A,p,q,r)

def Merge(A,p,q,r):
    i = p
    j = q+1
    k=0
    
    
    TEMP =  [0]*(r - p + 1)

    while i <= q and j <= r:
        if A[i] <= A[j]:
            TEMP[k] = A[i]
            k += 1
            i += 1
        else:  
            TEMP[k] = A[j] 
            k += 1
            j += 1
    
    """
        There are currently 2 cases
    1- i > q, means we exhausted left but there are elements in the right
    2- j > r, means we exhausted right but there are elements in the left
    """
    if (j > r):
        #  copy elements at the left side to temp
        while (i <= q):
            TEMP[k] = A[i]
            i += 1
            k += 1
    else:
        #  copy elements at the right side to temp
        while (j <= r):
            TEMP[k] = A[j]
            j += 1
            k += 1
    
    
    #  replace elements in A with elements in TEMP
    for t in range(k):
        A[p+t] = TEMP[t]



A = [15,16,13,10,19,18]
mergeSort(A,0,len(A)-1)
print(A)

答案 1 :(得分:0)

错误在于Merge()函数。

  1. 初始化i=p而不初始化i=1
  2. while循环终止后,i<qj<r可能会出现。我们也需要适应这些情况。
  3. 数组TEMP的大小不正确。
    更正了合并功能:
def Merge(A,p,q,r):
    i = p
    j = q+1
    k=0
    TEMP =  [0]*(r-p+1)
    
    while i <= q and j <= r:
        if A[i] <= A[j]:
            TEMP[k] = A[i]
            k += 1
            i += 1
        else:  
            TEMP[k] = A[j] 
            k += 1
            j += 1
    while i<=q:
        TEMP[k] = A[i]
        k+=1 
        i += 1
    while j<=r:
        TEMP[k] = A[j]
        k+=1 
        j += 1

    for t in range (p,r+1):
       A[t] = TEMP[t-p]

注意:请尝试使用更有意义的变量名。