[英]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:有两个问题:
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.