降序堆排序不起作用,尽管升序堆排序可以正常工作

时间:2018-07-04 22:53:30

标签: python algorithm data-structures heapsort min-heap

我试图用Python实现升序和降序的sortsort。似乎升序堆排序不能正常工作,尽管降序堆排序可以正常工作。我参加下面的代码和测试用例。我使用了here中所述的降序堆排序算法,并用Java中的示例代码仔细检查了我的代码,但仍然输出错误的结果。有什么帮助吗?

def max_heapify(A, n, i):
    maxIndex = i 
    left = 2 * i + 1
    right = 2 * i + 2

    if left < n and A[left] > A[maxIndex]:
        maxIndex = left 

    if right < n and A[right] > A[maxIndex]:
        maxIndex = right 

    if maxIndex != i:   
        A[i], A[maxIndex] = A[maxIndex], A[i]
        max_heapify(A, n, maxIndex)

def min_heapsort(A):
    n = len(A)

    for i in range(n//2, -1, -1):
        max_heapify(A, n, i)

    for i in range(n-1, 0, -1):
        A[i], A[0] = A[0], A[i]
        max_heapify(A, i, 0)

    return A

def min_heapify(A, n, i):

    minIndex = i 
    left = 2 * i + 1
    right = 2 * i + 2

    if left < n and A[left] < A[minIndex]:
        minIndex = left 

    if right < n and A[right] < A[minIndex]:
        minIndex = right 

    if minIndex != i:   
        A[i], A[minIndex] = A[minIndex], A[i]

def max_heapsort(A):
    n = len(A)

    for i in range(n//2, -1, -1):
        min_heapify(A, n, i)

    for i in range(n-1, -1, -1):
        A[i], A[0] = A[0], A[i]
        min_heapify(A, i, 0)

    return A

A = [7, 6, 5, 4, 3, 2, 1]
print min_heapsort(A) # [1, 2, 3, 4, 5, 6, 7], correct

A = [1, 2, 3, 4, 5, 6, 7]
print max_heapsort(A) # [7, 6, 4, 5, 3, 2, 1], wrong

0 个答案:

没有答案