STL源碼剖析之算法:random_shuffle

這個算法將[first, last)的元素次序隨機重排。也就是說,在N!中可能的排列中隨機選出一種,此處N爲last-first。這個算法詳述於Donald Knuth的《計算機程序設計藝術》3.4.2節。算法正確性的證明可以參考《算法導論》5.3節。

  1. template <class RandomAccessIterator>                                             
  2. inline void random_shuffle(RandomAccessIterator first, RandomAccessIterator last) { 
  3.     if(first != last)                                                             
  4.         for(RandomAccessIterator i = first + 1; i != last; ++i)                   
  5.             iter_swap(i, first + (rand() % ((i - first) + 1)));                   

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章