The following algorithm can sort three variables x
, y
and z
of type K
which are comparable using operator<
:
void sort2(K& x, K& y) {
if(y < x)
swap(x, y);
}
void sort3(K& x, K& y, K& z) {
sort2(x, y);
sort2(y, z);
sort2(x, y);
}
This needs three swaps in the "worst case". However basic mathematics tells us, that the ordering of three values can be done using only two swaps.
Example: The values (c,b,a) will be sorted using three swaps: (c,b,a) -> (b,c,a) -> (b,a,c) -> (a,b,c). However one swap would have been enough: (c,b,a) -> (a,b,c).
What would be the simplest algorithms which sorts three variables with at most two swaps in all cases?
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…