This corresponds to the sorting description of 5 elements in 7 comparisons
:
import random n=5 ran=[int(n*random.random()) for i in xrange(n)] print ran def selection_sort(li): l=li[:] sl=[] i=1 while len(l): lowest=l[0] for x in l: if x<lowest: lowest=x sl.append(lowest) l.remove(lowest) print i i+=1 return sl print selection_sort(ran)
It uses Selection Sort , which is NOT the most efficient, but uses very few comparisons.
This can be reduced to:
def ss(li): l=li[:] sl=[] while len(l): sl.append(l.pop(l.index(min(l)))) return sl
In any case, it prints something like this:
[0, 2, 1, 1, 4] 1 2 3 4 5 [0, 1, 1, 2, 4]
Perl has a wonderful module called Algorithm :: Networksort that allows you to play with them. The Bose-Nelson algorithm is quoted by Knut for several comparators, and you can see it here .
Edit
sorting insert also works well:
def InsertionSort(l): """ sorts l in place using an insertion sort """ for j in range(1, len(l)): key = l[j] i = j - 1 while (i >=0) and (l[i] > key): l[i+1] = l[i] i = i - 1 l[i+1] = key
source share