This appears a simple problem: given numbers a, b, c, d, e, swap them around so as to place the median in c and partition the others around it. I.e. the postcondition is: a <= c && b <= c && c <= d && c <= e.

Searching the Net for this isn't easy. Fortunately "our own" Xinok has the best of breed result, see http://stackoverflow.com/questions/11065963/possible-to-partition-five-elements-by-median-with-six-comparisons.

His algorithm is a little suboptimal in that when given a sorted array, it sometimes leaves it unsorted. So I changed it to http://dpaste.dzfl.pl/5fb2238d9891 to fix that. If I count right, it also saves one swap: does 0-9 swaps instead of 0-10.

Ideally however, such an algorithm would do 0 swaps if the median is already in c. My algorithm may still swap d and e without necessity.

So there's got to be a better solution. Your challenge - should you choose to accept it :o) - is an algorithm that does the partitioning in 6 comparisons and <= 9 swaps, which is idempotent: when applied twice, it always does 0 swaps.


Andrei

Reply via email to