【问题标题】:Time complexity of already-descending-sorted array in HeapSortHeapSort中已经降序排序的数组的时间复杂度
【发布时间】: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


    【解决方案1】:

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

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

    【讨论】:

    • 同意 2) 和 3) 但排序后的数组是堆排序的。
    • @SaiBot 好的,已删除。
    • 糟糕。通过在日志中添加 n...1 项而不是将它们相乘来犯了一个错误!谢谢!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-10-27
    • 1970-01-01
    • 2020-09-15
    • 1970-01-01
    • 2013-03-14
    相关资源
    最近更新 更多