mugs
Lifer
- Apr 29, 2003
- 48,920
- 46
- 91
Originally posted by: TuxDave
Originally posted by: mugs
Originally posted by: ones3k
=========================================================
Question #1) Given k sorted streams where each stream could possibly be infinite in length, describe an efficient algorithm to merge the k streams into a new stream (also in sorted order).
This is a basic algorithm I came up with, in English.
Start by ordering the k streams by the value of their first item. Pick the first item off the first stream (because you know it's the smallest). Compare the new first item in the first stream to the second. If the item in the first stream is bigger than the item in the second stream, iterate through the streams until you find the first stream's new correct spot, and move it there. Pick the first item off the new first stream. Repeat.
I kinda had the same idea. Sort the k streams by the first element. Take one off the top stream and look at the next element. I know that when you move this stream down to the correct sorted location every first element of the stream it passes goes directly into the final stream without needing to look at it. I just can't figure out the last optimization.
I'm not sure if I'm understanding you correctly... are you saying that as you move the "old" first stream down to its correct position, you'd take the first element off each stream it passes and put it directly into your result stream? That's not necessarily true.
Take this example:
Stream 1 = 1, 15, 16, 17
Stream 2 = 2, 3, 4, 5, 8, 10
Stream 3 = 6, 9, 11
Stream 4 = 16, 20, 60
After you pop the 1 off stream 1, it goes down between streams 3 and 4, but if you take the 2 off stream 2 and the 6 off stream 3, you've put the 6 before the 3, 4 and 5 of stream 2.
If that's not what you were saying, disregard.