[英]Is python's heapq.heapify() faster on a list that is close to a heap?
Like the title says, I would like to know if python's heapq.heapify() will work faster on a list that is close to a heap or does it do the entire operation element by element on every list?正如标题所说,我想知道 python 的 heapq.heapify() 是否会在接近堆的列表上更快地工作,或者它是否在每个列表上逐个元素地执行整个操作?
I'm debating on how often to use heapify().我正在讨论使用 heapify() 的频率。
The obvious answer is yes.显而易见的答案是肯定的。 If you supply a sorted array to
heapify
it won't have to perform any swaps at all.如果你提供一个排序数组来
heapify
它根本不需要执行任何交换。 If you supply a reverse-sorted array it will have to perform the maximum number of swaps.如果您提供反向排序的数组,它将必须执行最大数量的交换。
That said, there is no benefit to pre-sorting the array before passing it to heapify
because the total time (ie analyzing and arranging the array, plus heapify
time) will exceed the maximum time required for heapify
to do its work on even the worst-case arrangement.也就是说,在将数组传递给
heapify
之前对其进行预排序没有任何好处,因为总时间(即分析和排列数组,加上heapify
时间)将超过heapify
完成其工作所需的最长时间,即使是最坏的-案例安排。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.