Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>A simple extension of merge sort's merge phase can do this in O(n lg m) time (where n = total number of items and m = number of lists), using a <a href="http://en.wikipedia.org/wiki/Priority_queue" rel="noreferrer">priority queue</a> (eg, a <a href="http://en.wikipedia.org/wiki/Heap_(data_structure)" rel="noreferrer">heap</a>). Pseudocode:</p> <pre><code>Let P = a priority queue of the sorted lists, sorted by the smallest element in each list Let O = an empty output list While P is not empty: Let L = remove the minimum element from P Remove the first element from L and add it to O If L is not empty, add L to P </code></pre> <p>And a simple (untested!) concrete implementation in C++:</p> <pre><code>#include &lt;list&gt; #include &lt;set&gt; template&lt;typename T&gt; struct cmp_list { bool operator()(const std::list&lt;T&gt; *a, const std::list&lt;T&gt; *b) const { return a-&gt;front() &lt; b-&gt;front(); } }; template&lt;typename T&gt; void merge_sorted_lists(std::list&lt;T&gt; &amp;output, std::list&lt;std::list&lt;T&gt; &gt; &amp;input) { // Use a std::set as our priority queue. This has the same complexity analysis as // a heap, but has a higher constant factor. // Implementing a min-heap is left as an exercise for the reader, // as is a non-mutating version std::set&lt;std::list&lt;T&gt; *, cmp_list&lt;T&gt; &gt; pq; for ( typename std::list&lt;std::list&lt;T&gt; &gt;::iterator it = input.begin(); it != input.end(); it++) { if (it-&gt;empty()) continue; pq.insert(&amp;*it); } while (!pq.empty()) { std::list&lt;T&gt; *p = *pq.begin(); pq.erase(pq.begin()); output.push_back(p-&gt;front()); p-&gt;pop_front(); if (!p-&gt;empty()) pq.insert(p); } } </code></pre>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload