Category: algorithms | Component type: function |
template <class BidirectionalIterator> inline void inplace_merge(BidirectionalIterator first, BidirectionalIterator middle, BidirectionalIterator last); template <class BidirectionalIterator, class StrictWeakOrdering> inline void inplace_merge(BidirectionalIterator first, BidirectionalIterator middle, BidirectionalIterator last, StrictWeakOrdering comp);
Inplace_merge combines two consecutive sorted ranges [first, middle) and [middle, last) into a single sorted range [first, last). That is, it starts with a range [first, last) that consists of two pieces each of which is in ascending order, and rearranges it so that the entire range is in ascending order. Inplace_merge is stable, meaning both that the relative order of elements within each input range is preserved, and that for equivalent [1] elements in both input range the element from the first range precedes the element from the second.
The two versions of inplace_merge differ in how elements are compared. The first version uses operator<. That is, the input ranges and the output range satisfy the condition that for every pair of iterators i and j such that i precedes j, *j < *i is false. The second version uses the function object comp. That is, the input ranges and the output range satisfy the condition that for every pair of iterators i and j such that i precedes j, comp(*j, *i) is false.
int main() { int A[] = { 1, 3, 5, 7, 2, 4, 6, 8 }; inplace_merge(A, A + 4, A + 8); copy(A, A + 8, ostream_iterator<int>(cout, " ")); // The output is "1 2 3 4 5 6 7 8". }
[1] Note that you may use an ordering that is a strict weak ordering but not a total ordering; that is, there might be values x and y such that x < y, x > y, and x == y are all false. (See the LessThan Comparable requirements for a fuller discussion.) Two elements x and y are equivalent if neither x < y nor y < x. If you're using a total ordering, however (if you're using strcmp, for example, or if you're using ordinary arithmetic comparison on integers), then you can ignore this technical distinction: for a total ordering, equality and equivalence are the same.