Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Finding the median value of an array?

Tags:

java

c++

arrays

I was wondering if it was possible to find the median value of an array? For example, suppose I have an array of size nine. Would it possible to find the middle slot of this array?

like image 1000
Steffan Harris Avatar asked Sep 11 '10 17:09

Steffan Harris


People also ask

How do you find the median of an array without sorting?

You can certainly find the median of an array without sorting it. What is not easy is doing that efficiently. For example, you could just iterate over the elements of the array; for each element, count the number of elements less than and equal to it, until you find a value with the correct count.

How do you find the median of an array in C++?

If the number of element in the array is odd, then find the (N/2)th element using nth_element() function as illustrated below and then the value at index (N/2) is the median of the given array.


2 Answers

Do it in one line like a pro:

return (arr[size/2] + arr[(size-1)/2]) / 2;

cast to a double if you're expecting a double, etc.

like image 161
i_use_the_internet Avatar answered Oct 08 '22 01:10

i_use_the_internet


If you want to use any external library here is Apache commons math library using you can calculate the Median.
For more methods and use take look at the API documentation

import org.apache.commons.math3.*;
.....
......
........
//calculate median
public double getMedian(double[] values){
 Median median = new Median();
 double medianValue = median.evaluate(values);
 return medianValue;
}
.......
  • For more on evaluate method AbstractUnivariateStatistic#evaluate

Calculate in program

Generally, median is calculated using the following two formulas given here

If n is odd then Median (M) = value of ((n + 1)/2)th item term.
If n is even then Median (M) = value of [((n)/2)th item term + ((n)/2 + 1)th item term ]/2

It is very easy as you have 9 elements (odd number).
Find the middle element of an array.
In your program you can declare array

//as you mentioned in question, you have array with 9 elements
int[] numArray = new int[9]; 

then you need to sort array using Arrays#sort

Arrays.sort(numArray);
int middle = numArray.length/2;
int medianValue = 0; //declare variable 
if (numArray.length%2 == 1) 
    medianValue = numArray[middle];
else
   medianValue = (numArray[middle-1] + numArray[middle]) / 2;
like image 36
Aniket Kulkarni Avatar answered Oct 08 '22 00:10

Aniket Kulkarni