0

You have n sorted linked lists, each of size n. The linked lists references are stored in an array. What is an efficient algorithm to merge the n linked lists into a single sorted linked list?

Since they are all sorted:

  1. Incorporate a loop
  2. Check the first node of all the sorted linked lists and sort them by comparing to each other.
  3. Proceed to next node and repeat until null is hit.

Is this the most efficient way of doing this?

AstroCB
  • 11,800
  • 20
  • 54
  • 68
  • Missing assumptions: are the elements in the linked list contiguous with each other, or interleaved? `{{1,2,3,5}, {4,7,9,11}}` would be valid/invalid? Do I have 3 linked lists with 3 elements apiece? (Clarifying that n.) – Makoto Jun 24 '12 at 04:38
  • yes separate each linked list is already sorted and has the exact same number of elements.. – user1477348 Jun 24 '12 at 04:42
  • So interleaving is OK then too? – Makoto Jun 24 '12 at 04:43
  • no i would suppose they are contiguous in the list. – user1477348 Jun 24 '12 at 04:50
  • Keyword: "N-way merge" (with tweaks for a linked list), e.g. http://stackoverflow.com/questions/5055909/algorithm-for-n-way-merge , http://stackoverflow.com/questions/2705366/merging-k-sorted-linked-lists-analysis should be `O(N*K)` time. –  Jun 24 '12 at 05:13
  • I think the title should be "Efficient way to *Merge* multiple *Sorted* Lists?" –  Jun 24 '12 at 05:19
  • (While N-way merge is the generic approach for this, I think Makoto is onto something ... if they are continuous min/max runs can be utilized.) –  Jun 24 '12 at 05:20
  • Possible duplicate of [Merging k sorted linked lists - analysis](http://stackoverflow.com/questions/2705366/merging-k-sorted-linked-lists-analysis) – AnukuL Jan 16 '17 at 12:49

1 Answers1

0

Just link them all together (or dump them into a single list) and use a general sort. That will give you nlog(n) performance. Your way is n^2.

JP Alioto
  • 43,483
  • 5
  • 85
  • 112
  • if you dump all the lists into an array in his example then it is n^2 (n lists of size n) – David Cheung Jun 24 '12 at 04:58
  • @DavidCheung No, it only takes linear time to put all the elements into a list. Yes, the list will have size of n^2, but it will only take nlogn time to sort. – JP Alioto Jun 24 '12 at 05:00
  • yes but you will be reading n lists of size n (n*n) to read through all the lists and form one large array, the full algorithm complexity is n^2 + nlogn which makes it n^2 – David Cheung Jun 24 '12 at 05:00
  • 1
    You could do it very efficiently by just linking the last of the first to the first of the second, etc. – JP Alioto Jun 24 '12 at 05:07
  • 2
    This can be done better since the *lists are already sorted*. It's just a N-way merge. –  Jun 24 '12 at 05:12