108. Median number

 

Three different integers abc are given. Print the median number.

 

Input. Three integers abc that do not exceed 1000 by absolute value.

 

Output. Print the median among three numbers.

 

Sample input

Sample output

11 3 7

7

 

 

SOLUTION

elementary

 

Algorithm analysis

Consider a brute force solution using a conditional operator. The median among a, b, c will be:

·        a, if b ≤ a ≤ c or b ≥ a ≥ c;

·        b, if a ≤ b ≤ c or a ≥ b ≥ c;

·        c, if a ≤ c ≤ b or a ≥ c ≥ b;

 

Consider a solution using the functions minimum and maximum. The median among a, b, c would be a + b + c – min(a, b, c) – max(a, b, c).

 

Consider a solution using sorting. Read three numbers into array of length 3 and sort it. The middle element of the array is the median of three input numbers.

 

Algorithm realization

Read the input data. Compute the answer using the formula and print it.

 

scanf("%d %d %d",&a,&b,&c);

if ((b <= a && a <= c) || (b >= a && a >= c)) res = a;

else if ((a <= b && b <= c) || (a >= b && b >= c)) res = b;

else res = c;

printf("%d\n",res);

 

Algorithm realization min and max functions

 

#include <stdio.h>

 

int a, b, c, res;

 

int min(int x, int y)

{

  return (x < y) ? x : y;

}

 

int max(int x, int y)

{

  return (x > y) ? x : y;

}

 

int main(void)

{

  scanf("%d %d %d",&a,&b,&c);

  res = a + b + c - min(a, min(b, c)) - max(a, max(b, c));

  printf("%d\n",res);

  return 0;

}

 

Algorithm realization sorting

 

#include <cstdio>

#include <algorithm>

using namespace std;

 

int m[3];

 

int main(void)

{

  scanf("%d %d %d",&m[0],&m[1],&m[2]);

  sort(m,m+3);

  printf("%d\n",m[1]);

  return 0;

}

 

Java realization

 

import java.util.*;

 

public class Main

{

  static int min(int x, int y, int z)

  {

    return Math.min(x, Math.min(y, z));

  }

 

  static int max(int x, int y, int z)

  {

    return Math.max(x, Math.max(y, z));

  }

   

  public static void main(String[] args)

  {

    Scanner con = new Scanner(System.in);

    int a = con.nextInt();

    int b = con.nextInt();

    int c = con.nextInt();

    int res = a + b + c - max(a, b, c) - min(a, b, c);

    System.out.println(res);

    con.close();

  }

}

 

Python realization

 

a, b, c = map(int, input().split())

res = a + b + c - min(a, b, c) - max(a, b, c)

print(res)