Wednesday, February 22, 2012

Merge N Sorted Lists/Arrays.


Design and implement an algorithm to merge N sorted arrays.


Approach:
1. Take the head of all the N sorted arrays in a min-heap.
2. Get the min element from the min-heap and output/store it.
3. now pull out another element from the array to which the min-element in 2. belonged and add it to the heap and heapify it.
4. now repeat 2. & 3. till all the elements in N sorted arrays are exhausted.




Number of arrays: 7
48 52 202 459 589 647 700 794 
72 227 257 513 545 
151 327 361 691 821 
29 30 363 753 938 
120 178 314 364 409 662 695 
181 240 378 472 556 584 756 760 871 
87 111 242 275 368 376 815 944 966 
Final merged lists data: 
29 30 48 52 72 87 111 120 151 178 181 202 227 240 242 257 275 314 327 361 363 364 368 376 378 409 459 472 513 545 556 584 589 647 662 691 695 700 753 756 760 794 815 821 871 938 944 966 

No comments:

Post a Comment