【发布时间】:2017-11-03 15:12:11
【问题描述】:
我正在尝试在 python 中创建一个 HeapSort 函数,使用一些辅助函数。
我正在尝试按照书上的说明进行操作,并使用诸如 fixHeap 之类的一些函数来恢复堆中的正确顺序,而节点不遵循规则:
def getMaxKnot(i,j,A):
k = max(A[i],A[j])
if k==A[i]:
return i
if k==A[j]:
return j
def fixheap(v,H): #basically restore an heap with a node not following heap rules
if (2*v+1)>len(H)-1:
return H
else:
u=getMaxKnot(2*v+1,2*v+2,H)
if H[u]>H[v]:
listoperations.swap(u,v,H) #swap item in position u and v
return fixheap(u,H)
现在,我基本上想创建一个在左树和右树上递归工作的 heapify 函数,使用我的函数 fixheap 来恢复正确的顺序。
我的想法如下:
def heapify(A):
if A==[]:
return A
else:
heapify(LEFT TREE)
heapify(RIGHT TREE)
fixheap(0,A)
关于如何将我的数组 A 划分为左树和右树的任何想法?
【问题讨论】:
-
什么是“辅助功能”?
-
我在网上看到的所有 heapify 版本都是基于一个函数,将数组转换为堆。所以我调用了 fixHeap 辅助函数,但基本上是一个简单的 def 函数
-
辅助,抱歉
标签: python recursion divide heapsort