几个使用C++11的算法例子,收藏下。

插入排序(Insertion Sort)

代码:

1
2
3
4
template <class FwdIt> void insertSort(FwdIt first, FwdIt last) {
for (auto i = first; i != last; ++i)
std::rotate(std::upper_bound(first, i, *i), i, std::next(i));
}

快速排序(Quick Sort)

代码:

1
2
3
4
5
6
7
8
9
10
template <class FwdIt, class Compare = std::less<typename FwdIt::value_type>>
void quickSort(FwdIt first, FwdIt last, Compare cmp = Compare{}) {
auto const N = std::distance(first, last);
if (N <= 1)
return;
auto const pivot = std::next(first, N / 2);
std::nth_element(first, pivot, last, cmp);
quickSort(first, pivot, cmp);
quickSort(pivot, last, cmp);
}