Category: algorithms | Component type: function |
template <class RandomAccessIterator> void nth_element(RandomAccessIterator first, RandomAccessIterator nth, RandomAccessIterator last); template <class RandomAccessIterator, class StrictWeakOrdering> void nth_element(RandomAccessIterator first, RandomAccessIterator nth, RandomAccessIterator last, StrictWeakOrdering comp);
The two versions of nth_element differ in how they define whether one element is less than another. The first version compares objects using operator<, and the second compares objects using a function object comp.
The postcondition for the first version of nth_element is as follows. There exists no iterator i in the range [first, nth) such that *nth < *i, and there exists no iterator j in the range [nth + 1, last) such that *j < *nth.
The postcondition for the second version of nth_element is as follows. There exists no iterator i in the range [first, nth) such that comp(*nth, *i) is true, and there exists no iterator j in the range [nth + 1, last) such that comp(*j, *nth) is true.
int A[] = {7, 2, 6, 11, 9, 3, 12, 10, 8, 4, 1, 5}; const int N = sizeof(A) / sizeof(int); nth_element(A, A + 6, A + N); copy(A, A + N, ostream_iterator<int>(cout, " ")); // The printed result is "5 2 6 1 4 3 7 8 9 10 11 12".
[1] The way in which this differs from partial_sort is that neither the range [first, nth) nor the range [nth, last) is be sorted: it is simply guaranteed that none of the elements in [nth, last) is less than any of the elements in [first, nth). In that sense, nth_element is more similar to partition than to sort. Nth_element does less work than partial_sort, so, reasonably enough, it is faster. That's the main reason to use nth_element instead of partial_sort.
[2] Note that this is significantly less than the run-time complexity of partial_sort.
privacy policy | | | contact us |
Copyright © 1993-2001 Silicon Graphics, Inc. All rights reserved. | | | Trademark Information |