-1

What is the time complexity to insert k new elements into the binary heap which contains already n elements? I have constraint that I need to insert k elements in 0(k + Log n) complexity.

Hint: use a bottom-up approach similar to that for heap construction.

user2454830
  • 193
  • 2
  • 2
  • 11

1 Answers1

1

There is no easy answer to this question.

A binary heap insertion will have average complexity of O(1) and worst-case of O(log N). The complexity will remain within that bound regardless of k, but the actual time taken to complete the operation (not time complexity; I believe you might be confusing the terms) will depend on the implementation, platform, and the way the wind is blowing.

The closes thing to a concrete answer in terms of time is that the time taken to insert k elements at best be linearly proportional to k and at worst proportional to log (x) integrated from N to k+N. For N significantly larger than k we can approximate the time taken to proportional to k log N.

For more info see: http://en.wikipedia.org/wiki/Binary_heap

quant
  • 21,507
  • 32
  • 115
  • 211
  • So why the answer is more complicated than just: O(k) for average and O(k log(n)) for worst-case? – Andriy Tylychko May 08 '14 at 11:36
  • Because `k log (N)` is proportional to the time taken for the first insertion multiplied by `k`, it's a good approximation for k << N, which the OP does not specify. The actual amount will be proportional to `log N` for the first insertion, `log (N+1)` for the second, and so until we get to `log (N+k)`. The total time taken is therefore the integral over that range multiplied by `k`. – quant May 08 '14 at 12:15
  • OK, so we have O(k log(n + k)) – Andriy Tylychko May 08 '14 at 12:20
  • @AndyT that's worse than the worst case... – quant May 08 '14 at 12:22
  • How do you get that the *average* complexity of insertion is `O(1)`? Seems like that's the *best case* time. Worst case is indeed `O(log n)`. – Jim Mischel May 08 '14 at 15:54
  • @JimMischel see the link at the bottom of the post. – quant May 10 '14 at 01:48
  • You know, I've looked at that page many times and never noticed the discussion of the average complexity. I just "knew" that insert in a binary heap is O(log n). Thanks for making me read that. – Jim Mischel May 10 '14 at 22:33