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
2010-09-11 17:35:41
+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
2010-09-11 17:36:08
Your answer is wrong. For example, consider an array with two elements: 3 and 75. Your answer gives the median as 75.
Turtle
2010-09-11 19:40:34
What *is* the median of {3, 75}?
Wouter Lievens
2010-10-11 09:59:18
+1
A:
In C++, you can use std::nth_element
; see http://cplusplus.com/reference/algorithm/nth_element/.
Oli Charlesworth
2010-09-11 17:36:22
+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
2010-09-11 17:42:02