I recently took my Computer Science exam and there was a question like that.
There are two max-heaps (array implemented). You need to come up with an algorithm that merges these two max-heaps and creates a new max-heap (array implemented)
Solution of the question is very intuitive that is:
- Merge two array
- Call heap rebuild
I looked in the Internet and encountered with same type of solutions.
However, I wrote a solution like that which I could not refute own my own.
My Algorithm
- Create index1 and index2 which points first element of heapArr1 and heapArr2
- Create a new heap array which has size of heapArr1.size + heapArr2.size
- In while loop
- compare index1 element of heapArr1 and index2 element of heapArr2
- Whichever is greater, write the result array and increment the index of the array that element taken until two arrays all traversed.
For example
Heap1: 12-5 -6-2-3
Heap2: 15-13-4-1-0
We wil first compare 15 and 12. Write 15
resultHeap: 15
Now compare 13 and 12
resultHeap: 15 - 13
Compare 4 and 12
resultHeap: 15 - 13 - 12
Compare 4 and 5
resultHeap: 15 - 13 - 12 - 4
if we go on like that we have
resultHeap: 15 - 13 - 12 - 5 - 6 - 4 - 2 - 3 - 1 - 0. And it is also a heap
Is this algorithm correct? Or can someone gave the refutation data set?