20

Possible Duplicates:
Merging two sorted lists
Algorithm for N-way merge

Given k sorted arrays each of length n, construct a single merged and sorted array.focus on running time and space complexity.

Source : Amazon interview question.
Any thoughts? thanks

Community
  • 1
  • 1
Josh Morrison
  • 6,958
  • 20
  • 63
  • 84

1 Answers1

23

Make a heap from the first element in each array. Pop the head element from the heap, insert it into the result array, and then take the next element from the array the head of the heap came from, and insert that into the heap. Repeat until you consume all of the arrays.

Null Set
  • 5,252
  • 20
  • 36
  • 3
    Isn't this extremely inefficient since the conditions described in the OP describe a mergesort that's part of the way done? Think about it. You have some number of sorted arrays that you're going to merge into a sorted array. You already have the conditions for a mergesort. I'm not trying to pick holes in your idea, it's just that I'm just digging deeper into sorting algorithms and trying to learn as much as I can. – Michael McTiernan Mar 21 '11 at 07:00
  • 4
    @Michael This basically is a merge sort. I've just extended it to merging more than two sorted lists. The point of the heap is that it can find the minimum of the updated set of candidates in sublinear time, O(log(n)). At least that was the idea. – Null Set Mar 21 '11 at 07:05
  • @Michael or rather I meant to say, this is basically the merge step of the merge sort algorithm. – Null Set Mar 21 '11 at 07:08
  • 6
    @Michael McTiernan: No. You misunderstood. Null Set is not proposing dumping all the input array elements onto a heap - that would indeed be very inefficient. What Null Set is proposing is building a heap that contains only `k` elements: it includes the first (minimal) element from each sorted array. Just one element from each array. When you remove the minimum element from the heap (and send it to output), you add the next element from the same array to the heap and rebuild the heap. This way the size of the heap is always only `k`. – AnT Mar 21 '11 at 07:15
  • 1
    This is basically that schoolbook approach to merging *two* sorted arrays, but extended from two arrays to `k` arrays by using a heap for choosing the minimum from `k` elements. In this approach the fact that the sorting is partially done *is* intensively used by this algorithm. – AnT Mar 21 '11 at 07:19
  • 5
    note that this solution is optimal. assume you could do it better then O(n*logk(k)) - in this case you would be able to split every array into n sorted sub arrays of size 1, and sort it, with a better complexity then O(n*log(n)). since sorting is proven omega(n*logn), you get a contradiction. – amit Mar 22 '11 at 18:29
  • Is there an implementation for this in any library, if you guys know ? – Rajat Gupta Feb 03 '14 at 13:12
  • Can anyone help with the Java code of this solution? – Hengameh Jul 03 '15 at 08:02