The MCTS: Microsoft Exchange Server 2010 certification validates your skills in supporting the maintenance and administration of the Exchange servers in an enterprise environment. Learn everything you need to know with this course.
class Program
{
static void Main(string[] args)
{
Console.WriteLine(GetMedian(1, 3, 5, 6));
Console.ReadKey();
}
static int GetMedian(params int[] values)
{
Array.Sort(values);
if (values.Length % 2 == 0)
{
int lowMedian = values[(values.Length / 2) - 1];
int highMedian = values[values.Length / 2];
return (lowMedian + highMedian) / 2;
}
else
return values[(values.Length - 1) / 2];
}
}
static int GetMedian(int a, int b, int c)
{
int[] values = new int[] { a, b, c };
Array.Sort(values);
return values[1];
}
int getMedian4(int a, int b, int c)
{
if( a > b ) a ^= b, b ^= a, a ^= b;
if( b > c ) c ^= b, b ^= c, c ^= b;
if( a > b ) a ^= b, b ^= a, a ^= b;
return b;
}
OUTPUT:int getMedian1(int a, int b, int c);
int getMedian2(int a, int b, int c);
int getMedian3(int a, int b, int c);
int getMedian4(int a, int b, int c);
void foo( int (*getMed)(int, int, int) ) {
printf("%d %d %d %d %d %d %d %d %d %#0x\n",
getMed(1,2,3),
getMed(1,3,2),
getMed(2,1,3),
getMed(2,3,1),
getMed(3,1,2),
getMed(3,2,1),
getMed(3,2,2),
getMed(1,1,2),
getMed(1,2,1),
getMed(0x7F000000,2,0x74000000)
);
}
int main() {
foo( getMedian1 );
foo( getMedian2 );
foo( getMedian3 );
foo( getMedian4 );
}
int getMedian1(int a, int b, int c)
{
if (a <= b && b <= c || c <= b && b <= a)
return b;
if (b <= a && a <= c || c <= a && a <= b)
return a;
if (a <= c && c <= b || b <= c && c <= a)
return c;
}
int getMedian2(int a, int b, int c)
{
if( a <= b ){
if( b <= c ){
return b;
}else if( c <= a ){
return a;
}else{
return c;
}
}else{/* a > b */
if( b > c ){
return b;
}else if( c > a ){
return a;
}else{
return c;
}
}
}
int getMedian3(int a, int b, int c)
{
if (a <= b && b <= c || c <= b && b <= a)
return b;
if ( (a+c <= b) ^ ( a<=c ) )
return a;
// if (a <= c && c <= b || b <= c && c <= a) */
return c;
}
#define SWAP2int(x,y) { register int tmp = x; x = y; y = tmp; }
int getMedian5(int a, int b, int c)
{
if( a > b ) SWAP2int(a,b); // Note: the trailing ; is superflous, but nice to have, especially for maintenance reasons
if( b > c ) SWAP2int(b,c);
if( a > b ) SWAP2int(a,b);
return b;
}
inline void SWAP2int(int &x, int &y) { register int tmp = x; x = y; y = tmp; }
inline int getMedian5(int a, int b, int c)
{
if( a > b )
SWAP2int(a,b);
if( b > c )
SWAP2int(b,c);
if( a > b )
SWAP2int(a,b);
return b;
}
int maximum(int a, int b, int c)
{
return a >= b && a >= c ? a
: b >= c ? b
: c;
}
int minimum(int a, int b, int c)
{
return -maximum(-a, -b, -c);
}
int median(int a, int b, int c)
{
return a+b+c - maximum(a,b,c) - minimum(a,b,c);
}
#include <algorithm>
int getMedian(int a, int b, int c)
{
return std::sort(&a, &a+3),b;
}
Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.
Have a better answer? Share it in a comment.
Open in new window