tags:

views:

158

answers:

4

Hello, 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?

+1  A: 
vector<int> v;
size_t len = v.size;
nth_element( v.begin(), v.begin()+len/2,v.end() );

int median = v[len/2];
Kirill V. Lyadvinsky
+1  A: 

In java :

int middleSlot = youArray.length/2;
yourArray[middleSlot];

or

yourArray[yourArray.length/2];

in one line.

That's possible because in java arrays have a fixed size.

Note : 3/2 == 1


Resources :

Colin Hebert
Your answer is wrong. For example, consider an array with two elements: 3 and 75. Your answer gives the median as 75.
Turtle
What *is* the median of {3, 75}?
Wouter Lievens
+1  A: 

In C++, you can use std::nth_element; see http://cplusplus.com/reference/algorithm/nth_element/.

Oli Charlesworth
+2  A: 

Assuming the array x is sorted and is of length n:

If n is odd then the median is x[(n-1)/2].
If n is even than the median is ( x[n/2] + x[(n/2)-1] ) / 2.

Turtle