16 May 2024

Find The Median of The Given Array

FIND THE MEDIAN OF THE GIVEN ARRAY

The median is a fundamental statistical measure that represents the middle value of a dataset when arranged in order. It divides the dataset into two equal halves, making it a robust measure for understanding central tendency, especially in the presence of outliers.

What is the Median?

  • For an odd-sized array, the median is the middle element.
    Example: In [1, 3, 5, 7, 9], the median is 5.
  • For an even-sized array, the median is the average of the two middle elements.
    Example: In [1, 3, 5, 7], the median is (3+5)/2=4(3 + 5) / 2 = 4.

Steps to Find the Median

  1. Input: Start with an array of numbers.
  2. Sort: Arrange the array in ascending order.
  3. Determine:
    • If the array size is odd, pick the middle element.
    • If the array size is even, compute the average of the two middle elements.
CODE

import java.util.*;

class HelloWorld {

    public static void main(String[] args) {

        int n=sc.nextInt();

        int arr[]=new int[n];

        for(int i=0;i<n;i++){

            arr[i]=sc.nextInt();

        }

        Arrays.sort(arr);

        if(n/2==0){

            System.out.print((double)arr[(n/2)-1]+arr[n/2]/2);

        }

        else{

            System.out.print(arr[n/2]);

        }

    }

}

Applications of the Median

  • Used in statistics to analyze datasets.
  • Essential in financial analysis, such as calculating income or expenditure trends.
  • Helps in signal processing and machine learning to filter noise.

No comments:

Post a Comment