stable_quick_sort.h

Go to the documentation of this file.
00001 
00002 
00003 #ifndef stable_quicksort_h
00004 
00013 template<typename T, typename U>
00014 void concatinate_data( U& lhs, U& pivot, U& rhs, U& output_data)
00015 {
00016   using namespace std;
00017 
00018   output_data = lhs;
00019   copy( pivot.begin(), pivot.end(), back_insert_iterator<U >( output_data));
00020   copy( rhs.begin(), rhs.end(), back_insert_iterator<U >( output_data));
00021 }
00022 
00040 template<typename T, typename U>
00041 void stable_quick_sort( const U& input_data, U& output_data) 
00042 {
00043   using namespace std;
00044 
00045   if (input_data.size() <= 1) {
00046     output_data = input_data;
00047     return;
00048   } 
00049   int offset = input_data.size() / 2;
00050 
00051   U pivot( 1, input_data[offset]);
00052   U lhs, rhs;
00053   typename U::const_iterator pt;
00054   typename U::const_iterator pt_end;
00055 
00056   pt_end = input_data.begin() + offset;
00057   for (pt = input_data.begin();
00058        pt != pt_end;
00059        ++pt)
00060     {
00061       if (*pt < *pivot.begin()) {
00062         lhs.push_back( *pt);
00063       } else if (*pivot.begin() < *pt) {
00064         rhs.push_back( *pt);
00065       } else {
00066         if (pivot.size() == 1) {
00067           pivot.push_front( *pt);
00068         } else {
00069           pivot.insert( pivot.end()-1, *pt);
00070         }
00071       }
00072     }
00073 
00074   pt++ = pt_end;
00075   for (pt = input_data.begin(); 
00076        pt != input_data.end();
00077        ++pt)
00078     {
00079       if (*pt < *pivot.begin()) {
00080         lhs.push_back( *pt);
00081       } else if (*pivot.begin() < *pt) {
00082         rhs.push_back( *pt);
00083       } else {
00084         pivot.push_back( *pt);
00085       }
00086     }
00087 
00088   U lhs_sorted;
00089   stable_quick_sort< T, U>( lhs, lhs_sorted);
00090 
00091   U rhs_sorted;
00092   stable_quick_sort< T, U>( rhs, rhs_sorted);
00093 
00094   concatinate_data< T, U>( lhs_sorted, pivot, rhs_sorted, output_data);
00095 }
00096 
00097 #endif

Generated on Fri Jan 7 12:36:18 2011 for public_options by  doxygen 1.5.1