0

There's this question in the famous book "Introduction to Algorithms" by Udi Manber, which states that

Algorithm *Insert_To_Heap* may swap many times up the heap. Modify the algorithm so that at most one swap will be performed. O(log n) comparisons are still allowed.

I can't think of any such algorithm, and I even think that it is impossible(As if you insert the maximum element in a max heap it doesn't seem to get working any way). Some answers even exist which state that this is impossible.But considering this question to be from a good source, I am asking again if some you can give some good thought and find out what the author was trying to ask?

  • 1
    Unless he uses some word trick ("you can shift elements down and insert the new one in the empty spot, no swapping involved"), I don't see any way to achieve this. As you say, if you insert a new maximum, the current maximum has to move one level down the heap, so the element that was there must move too... that's 2 moves (=swaps?) already. – Vincent van der Weele Oct 02 '13 at 07:36
  • That's a nice thought of the word trick! may be he was trying to ask that :P But yes if we insert the max element, we need to shift the root to a level down and if both of the root children are occupied the shifts would go on. – Arkanath Pathak Oct 02 '13 at 07:47
  • Are we talking about just a regular binary heap? I doesn't seem possible. Maybe some context would help as to what "one swap" means. I mean, technically, you could rebuild the entire heap from scratch without "swapping" anything... – mrip Oct 02 '13 at 22:11
  • @mrip won't that require more than O(log n) comparisons? – Arkanath Pathak Oct 04 '13 at 04:00

1 Answers1

0

I think if we use a binary tree to implement the Heap, and every child contains pointer to its parent, we can finish Insert_To_Heap in just one insert operation and O(logN) comparison operations. However this may generate a node that has only one child, which would lead to a taller tree.

Guocheng
  • 543
  • 3
  • 15