News:

MyKidsDiary.in :: Capture your kids magical moment and create your Online Private Diary for your kids

Main Menu

Finding the Median

Started by aruljothi, Jun 11, 2009, 09:49 PM

Previous topic - Next topic

aruljothi


#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  );
}