我无法获得最大堆数组所需的输出,有人可以告诉我要进行的更改吗

I am not able to get the desired output for max heap array, can somebody tell me the changes to be made

python代码是:

def max_heapify(i, arr, n):
    l = 2*i
    r = 2*i+1
    largest = i
    if (2*i <= n-1 and arr[l] > arr[i]):
        largest = l

    if (2*i+1 <= n-1 and arr[r] > arr[largest]):
        largest = r
    if largest != i:
        temp = arr[largest]
        arr[largest] = arr[i]
        arr[i] = temp

        max_heapify(largest, arr, n)
    return arr

arr=[16,4,10,14,7,9,3,2,8,1]
n=len(arr)

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

试试这个

Python 堆排序程序

堆排序是一种基于二叉堆数据结构的比较排序技术。它类似于选择排序,我们首先找到最大元素并将最大元素放在最后。我们对剩余的元素重复相同的过程。

Python堆排序的实现程序

堆化以索引 i 为根的子树。

n 是堆的大小

def heapify(arr, n, i):

largest = i  # Initialize largest as root 

l = 2 * i + 1     # left = 2*i + 1 

r = 2 * i + 2     # right = 2*i + 2 



# See if left child of root exists and is 

# greater than root 

if l < n and arr[i] < arr[l]: 

    largest = l 



# See if right child of root exists and is 

# greater than root 

if r < n and arr[largest] < arr[r]: 

    largest = r 



# Change root, if needed 

if largest != i: 

    arr[i],arr[largest] = arr[largest],arr[i]  # swap 



    # Heapify the root. 

    heapify(arr, n, largest) 

对给定大小的数组进行排序的主要函数

def heapSort(arr):

n = len(arr) 



# Build a maxheap. 

for i in range(n, -1, -1): 

    heapify(arr, n, i) 



# One by one extract elements 

for i in range(n-1, 0, -1): 

    arr[i], arr[0] = arr[0], arr[i]   # swap 

    heapify(arr, i, 0) 

上面要测试的驱动程序代码

arr = [ 12, 11, 13, 5, 6, 7] 堆排序(arr)

n = len(arr)

打印 ("Sorted array is")

我在范围内(n):

print ("%d" %arr[i]), 

此代码由 Mohit Kumra 贡献

输出:

排序数组为 5 6 7 11 12 13