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

标签 algorithm sorting time-complexity analysis heapsort

考虑一个已经按降序排列的数组 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/

相关文章:

c++ - 如果求和是通过循环完成,则以下程序找到正确答案,但如果通过 GP 公式完成,则不正确。为什么?

algorithm - 在Go中回溯以找到有向非循环图的所有路径,将路径分配给解决方案 slice 时出现问题(Leetcode 797)

c++ - 制作一个用指针排序的有效算法

algorithm - 以 θ(n) 复杂度对数组进行排序

java - 在算法的复杂性中取什么作为n

algorithm - 有什么比蛮力更好的解决方案呢?

java - 如何递归求解 'classic' 背包算法?

c - 在 C 中创建大型数组时出现段错误

java - 我实现了一个自定义比较器来对 ArrayList 进行排序,但 listview 仍未排序

algorithm - 两种算法的复杂度