Finding the Median
#include <algorithm>
#include <vector>
#include <iostream>
using namespace std;
template <class T>
void print(T& c){
for( typename T::iterator i = c.begin(); i != c.end(); i++ ){
std::cout << *i << endl;
}
}
int main( ) {
const int len = 9;
const int a[len] = { 5, 6, 4, 3,2, 6, 7, 9, 3 };
vector<int> v( a, a+len );
print( v );
// midpoint is the median
nth_element( v.begin(), v.begin()+len/2,v.end() );
print( v );
cout << "\nMedian salary: " << v[len/2];
// display sorted v for clarity
sort( v.begin(), v.end() );
print( v );
}
Related examples in the same category