简体   繁体   English

使用 python 构建最大堆我遇到了错误的 output

[英]Building max heap using python i'm encountered with wrong output

i'm trying to build max heap in python i have done but after heapify the list output is not satisfy the max heap property.我正在尝试在 python 中构建最大堆,但在堆化列表后 output 不满足最大堆属性。 Can any one help to fix this issue任何人都可以帮助解决这个问题

def max_heapify(arr,i):
    left = 2 *i 
    right = 2 * i + 1
    length = len(arr)-1
    largest = i
    if length > left and arr[largest] < arr[left]:
        largest = left
    if length > right and arr[largest] < arr[right]:
        largest = right
    if largest != i:
        arr[largest],arr[i] = arr[i],arr[largest]
        max_heapify(arr,largest)
def build_max_heap(arr):
    for i in reversed(range(len(arr)//2)):
        max_heapify(arr,i)
    return arr

arr = [1,12,9,5,6,10]
print(build_max_heap(arr))

i'm getting out put [12, 9, 6, 5, 1, 10] which is not satisfy max heap property我正在输出不满足最大堆属性的 [12, 9, 6, 5, 1, 10]

There are two issues:有两个问题:

  • First, the heap is 0-based (the root is at index zero), so the children of node 0 will be 1 and 2, and hence the children of node i will be 2*i+1 and 2*i+2首先,堆是基于 0 的(根在索引 0 处),因此节点 0 的子节点将是 1 和 2,因此节点 i 的子节点将是 2*i+1 和 2*i+2
  • Your code compared the two children before swapping, but it has not compared the larger child with the parent, and it should only swap if the child is larger than the parent您的代码在交换之前比较了两个孩子,但它没有将较大的孩子与父母进行比较,并且只有当孩子大于父母时才应该交换
def max_heapify(arr,i):
    left = 2 *i + 1
    right = 2 * i + 2
    length = len(arr)
    largest = i
    if length > left and arr[largest] < arr[left]:
        largest = left
    if length > right and arr[largest] < arr[right]:
        largest = right
    if arr[largest] > arr[i]:
        arr[largest], arr[i] = arr[i],arr[largest]
        max_heapify(arr,largest)

def build_max_heap(arr):
    N = len(arr)
    for i in reversed(range(len(arr)//2)):
        max_heapify(arr,i)
    return arr

arr = [1,12,9,5,6,10]
print(build_max_heap(arr))

arr = [1,12,9,5,6,10,13]
print(build_max_heap(arr))


output:
[12, 6, 10, 5, 1, 9]                                                                                                                                                               
[13, 12, 10, 5, 6, 1, 9] 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM