U have 5 NOs , X1,X2,X3,X4,X5
With minimum no. of comparisons we have to find a median.
SWAP(X,Y) function is available to u .
I have a answer of six comparisons and eight swaps....wait for people to find out by themselves.
With minimum no. of comparisons we have to find a median.
SWAP(X,Y) function is available to u .
I have a answer of six comparisons and eight swaps....wait for people to find out by themselves.
Courtesy orkut ....did not verified as could not get the logic completely.
ReplyDeleteint median_of_5(int * x) {
if ( x[0] < x[1] ) swap( &x[0], &x[1] ) ;
if ( x[2] < x[3] ) swap( &x[2], &x[3] ) ;
if ( x[0] < x[2] ) { swap( &x[0], &x[2] ) ; swap( &x[1], &x[3] ) ; }
if ( x[1] < x[4] ) swap( &x[1], &x[4] ) ;
if ( x[1] < x[2] ) { swap( &x[1], &x[2] ) ; swap( &x[3], &x[4] ) ; }
if ( x[2] < x[4] ) swap( &x[2], &x[4] ) ;
return (x[2]) ;
}