標籤:style blog http color os io
本文為senlie原創,轉載請保留此地址:http://blog.csdn.net/zhengsenlie
nth_element
------------------------------------------------------------------------------
描述:重新排序,使得[nth,last)內沒有任何一個元素小於[first,nth)內的元素,
但對於[first,nth)和[nth,last)兩個子區間內的元素次序則無任何保證。
思路:
1.以 median-of-3-partition 將整個序列分割為更小的左、右子序列
2.如果 nth 迭代器落於左序列,就再對左子序列進行分割,否則就再對右子序列進行分割
3.直到分割後的子序列長大於3,對最後這個待分割的子序列做 Insertion Sort
圖6-17
複雜度:O(n)
源碼:
template <class RandomAccessIterator>inline void nth_element(RandomAccessIterator first, RandomAccessIterator nth, RandomAccessIterator last) { __nth_element(first, nth, last, value_type(first));}template <class RandomAccessIterator, class T>void __nth_element(RandomAccessIterator first, RandomAccessIterator nth, RandomAccessIterator last, T*) { while (last - first > 3) { //採用 median-of-3-partition 。參數:(first,last,pivot)//返回一個迭代器,指向分割後的右段第一個元素RandomAccessIterator cut = __unguarded_partition (first, last, T(__median(*first, *(first + (last - first)/2), *(last - 1)))); if (cut <= nth) //如果 nth 落於右段,再對右段實施分割 first = cut; else //如果 nth 落於左段,對左段實施分割 last = cut; } __insertion_sort(first, last); //對分割後的子序列做 Insertion Sort}template <class RandomAccessIterator, class T>RandomAccessIterator __unguarded_partition(RandomAccessIterator first, RandomAccessIterator last, T pivot) { while (true) { while (*first < pivot) ++first; --last; while (pivot < *last) --last; if (!(first < last)) return first; iter_swap(first, last); ++first; }}
樣本:
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".