Please note that the way you have implemented it may require more than three comparisons. You can find a minimum of four values with only three comparisons under any circumstances (ie, better performing) in a number of ways.
For example, you can find the minimum "M1" of "A" and "B" (
M1=( A<B ? A : B );
), then find the minimum "N" of "C" and "M" (
M2=( C<M1 ? C : M1 );
) and finally return the minimum of "D" and "M2" (
return( D<M2 ? D : M2 );
).
Another way (which may be better if you can parallelize it) is to find the minimum "M" of "A" and "B" ( M=( A<B ? A : B );
) and in parallel find the minimum "N" of "C" and "D" ( N=( C<D ? C : D );
), then just return the minimum of "M" and "N" ( return( M<N ? M : N );
).
If you want to implement this second without using temporary "M" and "N", you can use the following comparison tool that uses the same rationale, but may not be optimized even by good compilers.
if( A<B ){
if( C<D ) return( A<C ? A : C );
else return( A<D ? A : D );
}
else {
if( C<D ) return( B<C ? B : C );
else return( B<D ? B : D );
}
If you want to generalize the problem to find the minimum of "n" numbers "a [0], a [1], ..., a [n-1]", with "n-1" comparisons. One of them is the following, which is generalization of the first algorithm quoted.
T = a[0] ;
for( i=1 ; i<n ; i=i+1 ){
if( T>a[i] ) T = a[i] ;
}
return T ;
The generalization of the second requires recursion, which is only worthwhile to compile optimally (without requiring stacking) and in this case it is good that there are ways to calculate in parallel.
This is done by finding the minimum "M" of the first half of the numbers, the minimum "N" of the second half and then returning the minimum of "M" and "N", where the recursion stop is the size sequence one, that the only number worked is the minimum.
Any questions?