- #include <iostream>
- #include <functional>
- #include <type_traits>
- template <typename T, size_t N>
- void print(T(&array)[N])
- {
- for (auto e: array) {
- std::cout <<e<<"\\t";
- }
- std::cout <<"\\n";
- }
- template <typename It>
- void print(It beg, It end)
- {
- for (;beg < end;++ beg) {
- std::cout <<*beg<<"\\t";
- }
- std::cout <<"\\n";
- }
- template <typename It, typename Cmp = std::less<typename std::iterator_traits<It>::value_type>>
- void insertSort(It beg, It end, Cmp cmp = Cmp())
- {
- if (beg == end) return ;
- It it, cur;
- typename std::iterator_traits<It>::value_type ins;
- for (cur = beg + 1;cur < end;++ cur) {
- for ((ins = *cur), (it = cur - 1);it >= beg && cmp(ins, *it); it --) {
- *(it + 1) = *it;
- }
- *(it + 1) = ins;
- }
- }
- int main()
- {
- int array[] = {1, 5, 3, 4, 8};
- insertSort(array, array + 5);
- print(array);
- return 0;
- }
- //该片段来自于http://www.codesnippet.cn/detail/2812201514311.html
来源: http://www.codesnippet.cn/detail/2812201514311.html