標籤:style blog http color os 2014
本文為senlie原創,轉載請保留此地址:http://blog.csdn.net/zhengsenlie
partition
------------------------------------------------------------------------
描述:partition 會將區間[first,last) 中的元素重新排列。所有被一元條件運算 pred 判定為 true 的元素,都會被放在區間的前段,
被判定為 false 的元素,都會被放在區間的後段。
partition 不穩定,不保證 partition 後元素保留在原始相對位置, stable_partition 穩定
思路:
1.first往下尋找,遇到"符合移動條件"(pred不成立)的就停下來
2.last往上尋找,遇到"符合移動條件"(pred成立)的就停下來
3.交換 *first 和 *last, ++first, --last
圖6-6d
複雜度:O(n)
源碼:
//所有被 pred 判定為 true 的元素,都被放到前段//被 pred 判定為 false 的元素,都被放到後段//不保證保留相對位置template <class BidirectionalIterator, class Predicate>BidirectionalIterator partition(BidirectionalIterator first, BidirectionalIterator last, Predicate pred) { while (true) { while (true) if (first == last) return first; else if (pred(*first)) ++first; else break; --last; while (true) if (first == last) return first; else if (!pred(*last)) --last; else break; iter_swap(first, last); ++first; }}
樣本:
int A[] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};const int N = sizeof(A)/sizeof(int);partition(A, A + N, compose1(bind2nd(equal_to<int>(), 0), bind2nd(modulus<int>(), 2)));copy(A, A + N, ostream_iterator<int>(cout, " "));// The output is "10 2 8 4 6 5 7 3 9 1".