标题中都说了一切。我正在寻找R等价的Python heapq.heapify()
。我找不到它,但我希望它存在于某处。
heapq
是一个堆队列实现模块,它的成员函数heapify
接受一个对象列表作为输入,并返回一个堆对象,该对象包含对作为堆成员的那些对象的引用。
答案 0 :(得分:0)
我通过移植找到的here的Matlab代码创建了这个heapify
R函数(这比从Python移植更容易,因为像R一样,Matlab使用1索引基线)。
只需将未排序的向量传递给函数,并指定是否要实现min-heapify
或max-heapify
。我与Python的heapq.heapify()
(默认为min-heapify
)进行了比较,结果相同。
heapify = function(input_vector, min){
# below is the maxheapify algorithm
# minheapify = maxheapify with sign change at the beginning and at the end
if (min==TRUE){input_vector = - input_vector}
count = length(input_vector)
start = floor(count/2)
while (start >= 1){
root = start
theEnd = count
while ((root * 2) <= theEnd){
child = root * 2
if ((child + 1 <= theEnd) & (input_vector[child] < input_vector[child+1])){
child = child + 1
}
if (input_vector[root] < input_vector[child]){
temp = input_vector[root]
input_vector[root] = input_vector[child]
input_vector[child] = temp
root = child
} else {
break
}
}
start = start - 1
}
if (min==TRUE){input_vector = - input_vector}
output = list(heap=input_vector)
}
示例:
R中的
heapify(c(30,1,1,0,3,3,3,2,14,25,3,10,4,3),min=TRUE)$heap
[1] 0 1 1 2 3 3 3 30 14 25 3 10 4 3
Python中的:
test = [30,1,1,0,3,3,3,2,14,25,3,10,4,3]
heapq.heapify(test)
test
Out: [0, 1, 1, 2, 3, 3, 3, 30, 14, 25, 3, 10, 4, 3]