Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>The first improvement would be to simplify the three cases in the main loop: Rather than iterating while some of the sequence has elements, iterate while <em>both</em> sequences have elements. When leaving the loop, one of them will be empty, we don't know which, but we don't care: We append them at the end of the result.</p> <pre><code>def msort2(x): if len(x) &lt; 2: return x result = [] # moved! mid = int(len(x) / 2) y = msort2(x[:mid]) z = msort2(x[mid:]) while (len(y) &gt; 0) and (len(z) &gt; 0): if y[0] &gt; z[0]: result.append(z[0]) z.pop(0) else: result.append(y[0]) y.pop(0) result += y result += z return result </code></pre> <p>The second optimization is to avoid <code>pop</code>ping the elements. Rather, have two indices:</p> <pre><code>def msort3(x): result = [] if len(x) &lt; 2: return x mid = int(len(x) / 2) y = msort3(x[:mid]) z = msort3(x[mid:]) i = 0 j = 0 while i &lt; len(y) and j &lt; len(z): if y[i] &gt; z[j]: result.append(z[j]) j += 1 else: result.append(y[i]) i += 1 result += y[i:] result += z[j:] return result </code></pre> <p>A final improvement consists in using a non recursive algorithm to sort short sequences. In this case I use the built-in <code>sorted</code> function and use it when the size of the input is less than 20:</p> <pre><code>def msort4(x): result = [] if len(x) &lt; 20: return sorted(x) mid = int(len(x) / 2) y = msort4(x[:mid]) z = msort4(x[mid:]) i = 0 j = 0 while i &lt; len(y) and j &lt; len(z): if y[i] &gt; z[j]: result.append(z[j]) j += 1 else: result.append(y[i]) i += 1 result += y[i:] result += z[j:] return result </code></pre> <p>My measurements to sort a random list of 100000 integers are 2.46 seconds for the original version, 2.33 for msort2, 0.60 for msort3 and 0.40 for msort4. For reference, sorting all the list with <code>sorted</code> takes 0.03 seconds.</p>
    singulars
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. VO
      singulars
      1. This table or related slice is empty.
    2. VO
      singulars
      1. This table or related slice is empty.
    3. VO
      singulars
      1. This table or related slice is empty.
    1. This table or related slice is empty.
 

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