Problem Session Working in pairs of two, solve the following problem...

advertisement
Problem Session
Working in pairs of two,
solve the following problem...
Problem
Write a function that, given a vector of double values,
finds the median value for that vector.
If a sequence is sorted and has N values:
If N is odd:
the median is the middle value in the sequence.
Otherwise
the median is the average of the two values
in the middle of the sequence.
Your function should not assume that the sequence is
already sorted, and it should leave the vector’s values
in their original positions!
Coding
/* MyVectorOps.cpp
* ...
*/
#include <vector>
#include <algorithm>
using namespace std;
// vector
// sort()
double Median(vector<double> numVec)
{
sort(numVec.begin(), numVec.end());
// make a copy
int N = numVec.size();
// sort it
// size it
if (N % 2)
// N is odd:
return numVec[N/2];
// middle elem.
else
// N is even:
return (numVec[N/2 - 1] + numVec[N/2]) / 2.0;
}
Download