There are k lists, which contain m unsorted lists (0 <=m < k). How can the lists be merged into a single large list which should also be sorted, No information provided about the lists that are sorted.
-
sort the unsorted list before merging them. – Zac Aug 20 '12 at 22:33
-
You title talks of "both sorted and unsorted lists", but the description says "k lists, all sorted". Which is it? What do you mean by "instead of l(say 2)"? – Tony Delroy Aug 20 '12 at 23:11
-
i changed the question, thanks Tony ! – bicepjai Aug 21 '12 at 00:13
-
in practice just combining the lists and performing a [general sort can be faster (for small total number of items < 1e6) then a specialized algorithm (merge sort)](http://stackoverflow.com/a/482848/4279) despite worse asymptotic time complexity – jfs Aug 21 '12 at 00:28
3 Answers
Suppose n the number of the total elements in all lists.
Assuming this number of elements is distributed equally between all the lists, you can do the follows:
Sort every unsorted list
Merge all elements from all lists
Run-time analyze:
The number of elements in each list equals to n/k.
So sorting every unsorted list takes O((n/k)log(n/k) => run-time for sorting all m lists equals to O(m(n/k)*log(n/k)).
The merging part takes O(n).
Thus, we get overall run-time = O(n + m*(n/k)*log(n/k)).

- 972
- 7
- 17
you can use insertion sort which would be an easy answer. worst it would run O(n**2) per se.
Otherwise sort (merge, or quicksort) unsorted lists and merge them. based on your m and k you can do some micro optimziation. Here your complexity would be O(nlogn) based on n. you can figure out what it corresponds with k and m.

- 52,984
- 76
- 209
- 300
Sort the unsorted list using randomized quick sort and then merge all the sorted lists using merge sort .

- 26,489
- 43
- 149
- 227