heapq.merge的时间复杂度为何高于heapq.heapify的时间复杂度?

huangapple go评论45阅读模式
英文:

Why is the time complexity of heapq.merge higher than that of heapq.heapify?

问题

使用heapq.merge合并包含总共n个元素的k个排序列表应该具有O(n * logk)的复杂度。虽然这并没有直接列在文档中,但可以从维基百科文章中提到的直接k路合并中推断出来。这也似乎相当直观 - 你创建一个包含k个顶部元素的堆,然后弹出堆的根元素并将下一个元素从相同列表推入堆中 - 重复此操作直到堆(和供给它的列表)为空。

让我感到困惑的是,如果将heapq.heapify应用于以单个未排序列表提供的相同数量的元素n,那么该算法的复杂性高于后者。后者的复杂性已知为O(n)

这是没有道理的 - 应该是相反的。堆化n个无序元素应该比堆化相同的元素作为k个列表中的排序元素更困难。

我在这里漏掉了什么?

英文:

Merging k sorted lists containing a total of n elements using heapq.merge is supposed to have a complexity of O(n * logk). This is not directly listed in the documentation but can be inferred from the Wikipedia article mentioning the direct k-way merge. It also seems fairly intuitive - you create a heap of the k top elements and then pop the root of that heap and push onto the heap the next element from the same list - and repeat this till you get the heap (and the lists feeding to it) empty.

What bugs me is that the complexity of this algorithm is higher than that of heapq.heapify if the latter is applied on the same number of elements n supplied in a single unsorted list. The latter complexity is known to be O(n)

This does not make sense - it should be the other way round. It should be more difficult to heapify n unordered elements than to heapify the same elements as sorted in k lists.

What am I missing here?

答案1

得分: 2

直接的k路合并从已排序数组的输入中产生一个排序数组。

从所有未排序的n元素创建一个堆会产生一个堆。

堆不是一个排序列表;事实上,你需要做大量的工作才能从堆中产生一个排序列表,如有关堆排序的文章所讨论,它是一个O(n log n)的排序算法。因此,创建堆可能是O(n),但输出与k路合并的输出不同。在这个上下文中,您可以将它视为比已排序数组弱。因此,这个时间复杂度比k路合并的时间复杂度小是有道理的。

英文:

Direct k-way merge produces a sorted array from your input of sorted arrays.

Creating a heap from all your n elements in unsorted order produces, well, a heap.

A heap is not a sorted list; in fact you need to do a lot of work to produce a sorted list from a heap, as discussed in articles about heapsort, which is an O(n log n) sorting algorithm. So creating the heap may be O(n), but the output is different to that of k-way merge. In this context, you may view it as weaker than the already sorted array. Thus, it makes sense that this time complexity is smaller than that of k-way merge.

huangapple
  • 本文由 发表于 2023年2月9日 00:04:45
  • 转载请务必保留本文链接:https://go.coder-hub.com/75388531.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定