STL 源碼剖析 演算法 stl_algo.h -- nth_element

來源:互聯網
上載者:User

標籤: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".


聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.