STL中算法

sort

大数据量时,采用Quick Sort,分段递归排序;

小数据量时,采用Insert Sort。

如果迭代层次过深,会导致快排性能退化,这时采用Heap Sort排序。

快排pivot采用三点中值法,去整个序列的头尾中央三个元素,以其中值作为pivot

 

如果希望sort降序排序,引入头文件#include <functional>  用greater<int>()

#include <functional>
sort(vec.begin(), vec.end(),greater<int>() );    //降序

洗牌算法 random_shuffle

STL:

template <class _RandomAccessIter>
inline void random_shuffle(_RandomAccessIter __first,
                           _RandomAccessIter __last) {
  __STL_REQUIRES(_RandomAccessIter, _Mutable_RandomAccessIterator);
  if (__first == __last) return;
  for (_RandomAccessIter __i = __first + 1; __i != __last; ++__i) //从前往后
    iter_swap(__i, __first + __random_number((__i - __first) + 1)); //生成随机数进行交换
}

自己实现:

 

#include <ctime>
using namespace std;

void MySwap(int &x, int &y)
{
    int temp = x;
    x = y;
    y = temp;
}

void Shuffle(vector<int> num)
{
    srand((int)time(0));
    for (int i = num.size() - 1; i >= 1; i--)
    {
        MySwap(num[i], num[rand() % (i + 1)]);
    }
}

 

posted on 2016-09-05 14:48  已停更  阅读(234)  评论(0编辑  收藏  举报