use*_*980 7 python heap python-2.7 python-3.x heapq
def heapify(A):
for root in xrange(len(A)//2-1, -1, -1):
rootVal = A[root]
child = 2*root+1
while child < len(A):
if child+1 < len(A) and A[child] > A[child+1]:
child += 1
if rootVal <= A[child]:
break
A[child], A[(child-1)//2] = A[(child-1)//2], A[child]
child = child *2 + 1
Run Code Online (Sandbox Code Playgroud)
这是python heapq.heapify()的类似实现。据说在文档中此函数在O(n)中运行。但是,对于n / 2个元素,它似乎执行log(n)操作。为什么是O(n)?