0

When we have two binary min heaps implemented as doubly sorted linked links , what's the most efficient algorithm regarding the worst-case time to merge one heap into another ,

What I though myself, is that I would insert the elements of the heap with smaller number of elements in to the heap with larger number of elements :

If I have random access to elements (Which is usually not the case with linked list) it would be done in O(m * log(n+m)) where m < n because I can insert each element of smaller heap into the larger heap, otherwise it would be O(m * n) because I have to insert each element in to the least of already sorted list.

Is there any other idea that works faster and have better worst time ?

torrential coding
  • 1,755
  • 2
  • 24
  • 34
Arian
  • 7,397
  • 21
  • 89
  • 177

1 Answers1

1

You can do this in O(m + n) time easily, so long as you are able to keep track of which node you are examining in a traversal of the heap. In pseudo-code:

Iterator iterDest = largerHeap.getIterator();
Iterator iterSrc = smallerHeap.getIterator();

while (iterSrc.hasMore()) {
    valueSrc = iterSrc.getCurrent();
    valueDest = iterDest.getCurrent();

    if (valueSrc <= valueDest) {
        // Insert elements in their proper place in largerHeap
        iterDest.insertBeforeCurrent(valueSrc);
        iterSrc.moveNext();
    } else {
        if (iterDest.hasMore()) {
            iterDest.moveNext();
        } else {
            break;
        }
    }
}

// Append extra elements to the end of largerHeap
while (iterSrc.hasMore()) {
    largerHeap.append(iterSrc.getCurrent());
    iterSrc.moveNext();
}
torquestomp
  • 3,304
  • 19
  • 26
  • And what if it's implemented as unsorted doubly linked list with distinct members ? Does the distinction really help in terms of order of worst-case time in that case ? Well, a good algorithm is suggested here : http://stackoverflow.com/questions/1595333/merge-heaps-algorithm but does the distinction affect the time ? – Arian Apr 17 '13 at 18:54
  • The algorithm I've provided will not work if the linked lists are unsorted. You'd be far better off using a hash set or some other structure for detecting duplication in the unsorted case. – torquestomp Apr 17 '13 at 19:00