Write a program that displays the middle value of three unduplicated input values. Consider how easy or hard it would be to modify each of those algorithms to find the middle value rather than the smallest value. Then modify the algorithm you consider most appropriate for this problem.

## Expert Answer

import java.util.Scanner;

public class StatisticsDemo {

public static void main(String[] args) {

//initiating the scanner

Scanner sc = new Scanner(System.in);

System.out.println(“Enter value 1:”);

//taking input of the first element

int a = sc.nextInt();

System.out.println(“Enter value 2:”);

//taking input of the second element

int b = sc.nextInt();

System.out.println(“Enter value 3:”);

//taking input of the third element

int c = sc.nextInt();

//Calling the method “middle” where we are passing the three values as input

//and the method returns the middle value and storing the variable “middle”

int middle = middle(a, b, c);

System.out.println(“The middle value is : “+middle);

}

/*

* What iam trying to do is to sort the elements in increasing order

* So that the second number will be the median

* You can say that it is a mini version of selection sort

*/

private static int middle(int a, int b, int c) {

// effectively sort the values a, b & c

// putting smallest in a, median in b, largest in c

//intialising a variable to store values temporarily

int t;

/*comparing a and b if a>b then we are swapping the values of and b

* for example if a=6 , b=4 & c=5

* sinc a>b we are swapping the values as a=4 and b=6 now values are a=4,b=6,c=5

* then we check b>c since b>6 we swap the values

* now they are a=4,b=5,c=6

* then we check a>b again since the value of c is stored in b now

* if a>b we swap else the values will be same

* in our example a<b so the values are not swapped

* everytime the value will be in the variable b since we are sorting them in increasing order

*/

if (a > b) {

// swap a & b

t = a;

a = b;

b = t;

}

if (b > c) {

// swap b & c

t = b;

b = c;

c = t;

if (a > b) {

// swap a & b

t = a;

a = b;

b = t;

}

}

// b always contains the median value

return b;

}

}

Output: