0

Constructing a binary heap of size N from scratch takes NlogN compares on an average and thus linearithmic time.

Given that two binary heaps of size N are already in place, how to construct a single binary heap containing all 2N keys, in linear time (uses linear number of compares)?

Novneet Nov
  • 592
  • 1
  • 7
  • 22
  • 1
    Haven't thought about it but what if you just take root of your first heap and find a place for it in the second tree! – Sap Jul 23 '14 at 10:28
  • If the root of 1st tree is taken and placed in the 2nd tree in its proper place, it takes logN compares on an average. So for all the keys in the 1st tree (N keys) to be in the 2nd tree in takes linearithmic (NlogN) comapres and thus time. – Novneet Nov Jul 23 '14 at 10:36
  • Your first statement is incorrect. You can create a binary heap from an array of size N in O(N) time. See, for example, http://blog.mischel.com/2013/09/30/a-simple-heap-of-integers/ – Jim Mischel Jul 23 '14 at 16:37
  • Yeah. It can be constructed from an array of size N in O(N) time. – Novneet Nov Jul 23 '14 at 17:35

1 Answers1

5

Constructing a binary heap of size N from scratch takes NlogN compares on an average and thus linearithmic time.

If you mean "constructing a binary heap of size N from an array of size N", then this is not necessarily true. You can do it in linear time. See Building a heap here.

So for your problem, if you have your two heaps in two arrays, concatenating the arrays and running the same algorithm on the resulting array will be linear.

IVlad
  • 43,099
  • 13
  • 111
  • 179