gpt4 book ai didi

algorithm - HeapSort 中已经降序排列的数组的时间复杂度

转载 作者:塔克拉玛干 更新时间:2023-11-03 05:51:52 24 4
gpt4 key购买 nike

考虑一个已经按降序排列的数组 A[n]。堆已经建立。现在考虑我们将 A[1](数组索引从 1 开始)与 A[heap.size] 交换的循环。这是伪代码:

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 以通过允许它向下 float 到适当的位置来恢复堆属性。我们知道 Max-Heapify 将花费 clg(n) 时间。所以,循环不应该花费 c(lg (n) + lg (n-1) + .... + lg(1) ) = Theta(log(n)) 时间而不是 jut Theta ( n*lg(n))?因为每次迭代堆大小都在减小?

最佳答案

n..1 的对数和不是log(n) 而是nlogn(看斯特林公式)

从任意数组构建经典堆是 O(n) 过程 - 而不是 O(nlogn)

关于algorithm - HeapSort 中已经降序排列的数组的时间复杂度,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48334448/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com