#include <algorithm> #include <vector> #include <iostream> #include <functional> using namespace std; /* * generates: original order of the vector: 29 23 20 22 17 15 26 51 19 12 35 40 sorting vector based on element 26 12 15 17 19 20 22 23 26 51 29 35 40 sorting vector in descending order based on element 23 40 35 29 51 26 23 22 20 19 17 15 12 */ /************************************************************************/ /* */ template<class _Ty1, class _Ty2> struct my_pair { // store a pair of values typedef my_pair<_Ty1, _Ty2> _Myt; typedef _Ty1 first_type; typedef _Ty2 second_type; my_pair() : first(_Ty1()), second(_Ty2()) { // construct from defaults } my_pair(const _Ty1& _Val1, const _Ty2& _Val2) : first(_Val1), second(_Val2) { // construct from specified values } template<class _Other1, class _Other2> my_pair(const my_pair<_Other1, _Other2>& _Right) : first(_Right.first), second(_Right.second) { // construct from compatible pair } void swap(_Myt& _Right) { // exchange contents with _Right if (this != &_Right) { // different, worth swapping std::swap(first, _Right.first); std::swap(second, _Right.second); } } _Ty1 first; // the first stored value _Ty2 second; // the second stored value }; template<class _RanIt> inline void my_Nth_element(_RanIt _First, _RanIt _Nth, _RanIt _Last) { // order Nth element, using operator< _DEBUG_RANGE(_First, _Last); for (; _ISORT_MAX < _Last - _First; ) { // divide and conquer, ordering partition containing Nth pair<_RanIt, _RanIt> _Mid = std::_Unguarded_partition(_First, _Last); if (_Mid.second <= _Nth) _First = _Mid.second; else if (_Mid.first <= _Nth) return; // Nth inside fat pivot, done else _Last = _Mid.first; } std::_Insertion_sort(_First, _Last); // sort any remainder } /************************************************************************/ int main() { int ia[] = {29,23,20,22,17,15,26,51,19,12,35,40}; vector< int > vec( ia, ia + 12 ); ostream_iterator<int> out( cout, " " ); cout << "original order of the vector: "; copy( vec.begin(), vec.end(), out ); cout << endl; cout << "sorting vector based on element " << *( vec.begin() + 6 ) << endl; // partition the elements by the 6th element /*nth_element*/my_Nth_element( vec.begin(), vec.begin() + 6, vec.end() ); copy( vec.begin(), vec.end(), out ); cout << endl; cout << "sorting vector in descending order " << "based on element " << *( vec.begin() + 6 ) << endl; nth_element( vec.begin(), vec.begin()+6, vec.end(), greater<int>() ); copy( vec.begin(), vec.end(), out ); cout << endl; return 0; } /************************************************************************/ /* widely used to find out m elements which in n elements */ /************************************************************************/
nth_element使用的算法是快速划分。
它其实就是不完全的快速排序,只要递归地排序需要排序的部分就可以了。