算法合并两个最大堆? [英] Algorithm for merging two max heaps?

查看:1514
本文介绍了算法合并两个最大堆?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否有一个有效的算法用于合并被作为数组存储最多2个,堆?

Is there an efficient algorithm for merging 2 max-heaps that are stored as arrays?

推荐答案

这取决于什么堆的类型。

It depends on what the type of the heap is.

如果它是一个标准堆,每一个节点最多两个孩子,这得到填补的叶子上最多两个不同的行,你不能比为O(n)的合并变得更好。

If it's a standard heap where every node has up to two children and which gets filled up that the leaves are on a maximum of two different rows, you cannot get better than O(n) for merge.

只要把两个数组在一起,并创建一个新的堆出他们这需要为O(n)。

Just put the two arrays together and create a new heap out of them which takes O(n).

为了获得更好的性能合并,您可以使用另一种堆变像一个斐波那契堆它可以在O合并(1)摊销。

For better merging performance, you could use another heap variant like a Fibonacci-Heap which can merge in O(1) amortized.

更新: 需要注意的是它是更糟由一个插入的第一堆中的一个的所有元素到第二堆或反之亦然,因为一个插入需要O(的log(n))。 作为您的评论的状态,你似乎不知道如何堆是最佳建在一开始(再次标准二进制堆)

Update: Note that it is worse to insert all elements of the first heap one by one to the second heap or vice versa since an insertion takes O(log(n)). As your comment states, you don't seem to know how the heap is optimally built in the beginning (again for a standard binary heap)

  1. 创建一个数组,并把两个堆的元素在一些任意顺序
  2. 现在,开始在最低水平。最低级别包含琐碎的MAX-堆大小为1,所以这个层面做
  3. 将一个水平了。当堆子S被侵犯的一个堆条件,交换堆子的根源与它的大孩子。随后,2级是做
  4. 将要当堆条件被侵犯3级,过程和以前一样。交换下来与它的大孩子,递归过程,直到一切都符合最高级别3
  5. ...
  6. 当你到达山顶,你在O(n)的创建一个新的堆。

我省略了证明,但是在这里你能解释这一点,因为你已经做得最多的底部水平,你没有掉太多的内容,以堆的重新建立堆条件。你有更小的子堆,这是不是你会做什么,如果你需要插入每一个元素插入=>那么,您willoperate对整个堆每次它需要O(n)的每一次一个堆更好的操作

I omit a proof here but you can explain this since you have done most of the heap on the bottom levels where you didn't have to swap much content to re-establish the heap condition. You have operated on much smaller "sub heaps" which is much better than what you would do if you would insert every element into one of the heaps => then, you willoperate every time on the whole heap which takes O(n) every time.

更新2:一个二项堆允许为O合并(日志(N)),并会符合你的O(日志(N)^ 2)要求

Update 2: A binomial heap allows merging in O(log(n)) and would conform to your O(log(n)^2) requirement.

这篇关于算法合并两个最大堆?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆