September 29, 2018

# Write a java program to calculate median of the array

Write a java program to calculate median of the array. Write a program to accept an int array as input, and calculate the median of the same.

Median Calculation Procedure:

- Sort the sequence of numbers.
- The total number count is odd, Median will be the middle number.

The total number count is even, Median will be the average of two middle numbers, After calculating the average, round the number to nearest integer.

** Input and Output Format:**

Input consists of a an integer which denotes the size of the array followed by the array of integers.

Output consists of a integer.

Refer sample output for formatting specifications.

**Sample Input 1:**

7

1

2

1

4

7

1

2

**Sample Output 1:**

2

**Sample Input 2:**

6

52

51

81

84

60

88

**Sample Output 2:**

71

## Write a java program to calculate median of the array

import java.util.*; public class Main { public static void main(String[] args) { int n,m; Scanner sin = new Scanner(System.in); n = sin.nextInt(); int[] a1 = new int[n]; for(int i=0;i<n;i++) { a1[i] = sin.nextInt(); } System.out.println(""+calculateMedian(a1)); } } public static int calculateMedian(int[] a) { Arrays.sort(a); int length = a.length; int result=0,mid=0,midNext=0; if((length%2) != 0) { mid = (length/2)+1; result = a[mid]; } else { mid = length/2; midNext = mid+1; float add = a[mid-1]+a[midNext-1]; float div = add/2; result = Math.round(div); } return result; }