I have to model the execution plan of sorting a list of 5 elements, in python, using the minimum number of comparisons between elements. Other than that, the complexity is irrelevant.
The result is a list of pairs representing the comparisons needed to sort the list at another time.
I know there's an algorithm that does this in 7 comparisons (between elements, always, not complexity-wise), but I can't find a readable (for me) version.
How can I sort the 5 elements in 7 comparisons, and build an "execution plan" for the sort?
PD: not homework.
This fits your description of sorting
5 elements in 7 comparisons
:This uses a Selection Sort which is NOT the most efficient, but does use very few comparisons.
This can be shortened to:
In either case, prints something like this:
Perl has a lovely module called Algorithm::Networksort that allows you to play with these. The Bose-Nelson algorithm is cited by Knuth for few comparators and you can see it here.
Edit
An insertion sort also works well: