Tuesday, June 11, 2013

Finding the median of an array

Median of an array is defined as the middle element when it is sorted. The middle element is the one which divides the array into two equal halves if the array is of odd length. If the length is even, the average of two middle elements is median.

For example the median of
[4,3,2,5,1] is 3
Median of [6,1,3,5,4,2] is 3.5
The following is the Java code to calculate the median of an array.



import java.util.Arrays;
import java.util.Scanner;

/**
 *
 * @author Ravi
 */
public class Median {

    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) {
        int nSize;
        int [] array;
        Scanner reader = new Scanner(System.in);
        nSize = reader.nextInt();
        array = new int[nSize];
        for( int i = 0 ; i < nSize; i++)
        {
            array[i] = reader.nextInt();
        }
        
        System.out.println("Median: "+getMedian(array));
    }
    public static double getMedian(int [] array)
    {
        Arrays.sort(array);
        if( array.length % 2 == 0)
        {
            int m1 = array[ (array.length/2)-1];
            int m2 = array[ array.length/2];
            return (m1+m2)/2.0;
        }
        else
        {
            return array[ array.length /2 ];
        }
    }
}