Skip to content

Merging pre-sorted lists

A while ago, I came across an interesting problem. We have 3 different sorted queues (entries were sorted by time), out of which we had to pickup the smallest time, and send the first arrived entry out of those 3 queues in sequence.

Q1 Q2 Q3
2 3 1
5 4 6
7 6 9
8 10 11

As you can see, all queues (Q1, Q2, Q3) are already sorted, but on application side we have to pickup entries across all queues in sorted order and process them. So the entries should be processed in 1, 2, 3, 4, 5, … 11 sequence. Frankly this is merging of already sorted lists, and a person from computer science background should already know this. But I don’t come from such background, and the solution one of my friends gave was plain amazing.

The solution was pickup first entry from each queue, compare them, choose the smallest and process it first.

Q1 Q2 Q3 Smallest
2 3 1 1

Thus, here 1 is processed first. Now pickup next entry from queue where smallest was found (Q3 in this example), so now the next comparison becomes like this

Q1 Q2 Q3 Smallest
2 3 6 2

The smallest is 2, so this is processed and next entry from Q1 was picked-up

Q1 Q2 Q3 Smallest
5 3 6 3

And so on… giving us

Q1 Q2 Q3 Smallest
2 3 1 1
2 3 6 2
5 3 6 3
5 4 6 4
5 6 6 5
7 6 6 6
7 10 6 6
7 10 9 7
8 10 9 8
10 9 9
10 11 10
11 11

A simple, and elegant solution, isn’t it? Is there any other better alternative?

3 thoughts on “Merging pre-sorted lists”

Leave a Reply

Your email address will not be published. Required fields are marked *

11 + seventeen =