【发布时间】:2018-06-28 07:14:53
【问题描述】:
考虑一个已经按降序排序的数组 A[n]。堆已经建立。现在考虑我们用 A[heap.size] 交换 A[1](数组索引从 1 开始)的循环。这是伪代码:
Build-Max-Heap(A) //Already done
while (i > 0) {
swap(A[1] with A[heap_size]
heap_size = heap_size - 1
Max-Heapify(A,1) //Takes lg(A.heap_size) time to float the 1st element down to it's respective position
}
我们在元素 1 上调用 Max-Heapify 来恢复堆属性,允许它向下浮动到适当的位置。我们知道 Max-Heapify 将花费 clg(n) 时间。所以,循环不应该占用 c(lg (n) + lg (n-1) + .... + lg(1) ) = Theta(log(n)) 时间而不是 jut Theta ( n*lg(n))?因为堆大小随着每次迭代而减小?
【问题讨论】:
标签: algorithm sorting time-complexity analysis heapsort