GCC's implementation of qsort
uses the median-of-3 to choose a pivot. While at it, the 3 elements are sorted with a sorting network.
A sorting network for 3 elements would normally require 3 comparisons. But in this particular implementation, the last comparison can be skipped, depending on the comparison before:
if(a[0] > a[1]) swap(a[0], a[1]);
if(a[1] > a[2]) swap(a[1], a[2]);
else goto jump;
if(a[0] > a[1]) swap(a[0], a[1]);
jump:;
Could something similar be done for networks with n = 4...16
(the ones that have a known minimum optimal number of comparisons)? If so, which ones and what would they look like?
UPDATE: So far, I have found one other network, that allows skipping one comparison:
// sorting network for 5 elements
if (a[0] > a[1]) { SWAP(a[0], a[1]); }
if (a[2] > a[3]) { SWAP(a[2], a[3]); }
if (a[1] > a[3]) { SWAP(a[1], a[3]); }
if (a[2] > a[4]) { SWAP(a[2], a[4]); }
if (a[0] > a[2]) { SWAP(a[0], a[2]); }
if (a[1] > a[4]) { SWAP(a[1], a[4]); }
if (a[1] > a[2]) { SWAP(a[1], a[2]); }
if (a[3] > a[4]) { SWAP(a[3], a[4]); }
else { goto jump; }
if (a[2] > a[3]) { SWAP(a[2], a[3]); }
jump:;
I tested this with all permutations of 12345, and it sorts all of them correctly.