Median of three, pivot
<p>I'm looking for the <strong>median of three</strong>, using this for a pivot in a QuickSort. I would not like to import any statistics library because I believe it creates a bit of overhead which I would like to reduce as much as possible.</p>

<pre><code>def median(num_list):

if (num_list[0] &gt; num_list[len(num_list) - 1]) and (num_list[0] &lt; num_list[int(len(num_list)//2)]):
    return num_list[0]
elif (num_list[int(len(num_list)//2)] &gt; num_list[len(num_list) - 1]) and (num_list[0] &gt; num_list[int(len(num_list)//2)]):
    return num_list[int(len(num_list)//2)]
else:
    return num_list[len(num_list) - 1]
</code></pre>

<p>this seems to be returning the last else statement every time, I'm stumped...</p>

<p>In Quicksort you do not usually want just to know the median of three, you want to arrange the three values so the smallest is in one spot, the median in another, and the maximum in yet another. But if you really just want the median of three, here are two ways, plus another that rearranges.</p>

<p>Here's a short way to find the median of <code>a</code>, <code>b</code>, and <code>c</code>.</p>

<pre><code>return a + b + c - min(a, b, c) - max(a, b, c)
</code></pre>

<p>If you want only comparisons, and to get what may be the quickest code, realize that three comparisons may need to be executed but you want to try for only two. (Two comparisons can handle four cases, but there are six arrangements of three objects.) Try</p>

<pre><code>if a &lt; b:
    if b &lt; c:
        return b
    elif a &lt; c:
        return c
    else:
        return a
else:
    if a &lt; c:
        return a
    elif b &lt; c:
        return c
    else:
        return b
</code></pre>

<p>If you want to rearrange the values so <code>a &lt;= b &lt;= c</code>,</p>

<pre><code>if a &gt; b:
    a, b = b, a
if b &gt; c:
    b, c = c, b
if a &gt; b
    a, b = b, a
return b
</code></pre>

python quicksort