Finding the Median : nth_element « STL Algorithms Sorting « C++






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

1.Illustrating the generic nth_element algorithm
2.Use nth_element to extract the four lowest elements
3.Use nth_element to extract the four highest elements
4.Use nth_element with custom function to extract the four highest elements