Java Program to find Median of array elements

Program

import java.util.Scanner;
public class MedianOfArrayElements {
  private void calculateMedian(int n, double inputArray[]) {
    double median = 0;
    if (n % 2 == 1) {
      median = inputArray[((n + 1) / 2) - 1];
    } else {
      median = (inputArray[n / 2 - 1] + inputArray[n / 2]) / 2;
    }
    System.out.println("Median of the given array elements is: " + median);
  }
  public static void main(String[] args) {
    System.out.println("Enter the required size of the array: ");
    Scanner reader = new Scanner(System.in);
    int size = reader.nextInt();
    double inputArray[] = new double[size];
    System.out.println("Enter the elements of the array: ");
    for (int i = 0; i < size; i++) {
      inputArray[i] = reader.nextDouble();
    }
    MedianOfArrayElements medianOfArrayElements = new MedianOfArrayElements();
    medianOfArrayElements.calculateMedian(size, inputArray);
  }
}

This Java program calculates the median of the elements in an array.

  1. Input Array Size and Elements:

    • The user is prompted to enter the size of the array (size).
    • A double array inputArray[] is created to store the elements.
    • The user enters the elements of the array, which are stored in inputArray.
    • This program assumes the array is already sorted. If not, you need to sort the array before calculating the median (e.g., using Arrays.sort()).
    • The program works for any number of elements (integer or decimal) entered by the user.
  2. Median Calculation Method:

    • A method calculateMedian(int n, double inputArray[]) is defined to compute the median.
    • Median Definition:
      • If the array size (n) is odd, the median is the middle element of the sorted array.
      • If n is even, the median is the average of the two middle elements in the sorted array.
    • Formula:
      • For an odd-sized array: median = inputArray[(n + 1) / 2 - 1].
      • For an even-sized array: median = (inputArray[n / 2 - 1] + inputArray[n / 2]) / 2.
  3. Output:

    • The calculated median is displayed.

Example Usage:

  1. For an array [1, 3, 5] (size 3, odd): Median = 3.
  2. For an array [2, 4, 6, 8] (size 4, even): Median = (4 + 6) / 2 = 5.

Output

javac .\MedianOfArrayElements.java
java MedianOfArrayElements        
Enter the required size of the array: 
5
Enter the elements of the array: 
10
10.5
11
11.5
12
Median of the given array elements is: 11.0