Write a program to find the median of an array.
A median is the middle value - that is to say it has equal number of elements which are smaller and those which are larger.
So obviously, the array need to be sorted. And once we have a sorted array, the n/2th element is the median.
As simple as that.
But what if the array has even number of elements? In that case we have to find half of sum middle two elements .
Here is the complete program.
import java.util.Arrays; import java.util.Scanner; public class ArrayMedian { public static void main(String args[]){ int n ; System.out.println("Size of array="); Scanner scanner = new Scanner(System.in); n = scanner.nextInt(); int arr[] = new int[n]; System.out.println("Enter array elements:"); for(int i=0;i<n;i++) arr[i] = scanner.nextInt(); Arrays.sort(arr); double median; if(n%2==0){ median =( arr[n/2]+arr[n/2-1])/2.0; }else{ median = arr[n/2]; } System.out.println("Median of the array="+median); } }
Comments
Post a Comment