【C++】C++11 STL算法(十):使用STL实现排序算法

【C++】郭老二博文之:C++目录

一、快速排序

1、适用于c++11版本

template <class ForwardIt>
void quicksort(ForwardIt first, ForwardIt last)
{
	if(first == last) return;
	auto pivot = *std::next(first, std::distance(first,last)/2);

	ForwardIt middle1 = std::partition(first,   last, [pivot](const decltype(*std::declval<ForwardIt>()) &em){ return em < pivot; });
	ForwardIt middle2 = std::partition(middle1, last, [pivot](const decltype(*std::declval<ForwardIt>()) &em){ return !(pivot < em); });

	quicksort(first, middle1);
	quicksort(middle2, last);
}

2、适用于c++14版本

template <class ForwardIt>
void quicksort(ForwardIt first, ForwardIt last)
{
	if(first == last) return;
	auto pivot = *std::next(first, std::distance(first,last)/2);

	ForwardIt middle1 = std::partition(first,   last, [pivot](const auto& em){ return em < pivot; });
	ForwardIt middle2 = std::partition(middle1, last, [pivot](const auto& em){ return !(pivot < em); });

	quicksort(first, middle1);
	quicksort(middle2, last);
}

二、选择排序

template<class ForwardIt>
void selection_sort(ForwardIt begin, ForwardIt end)
{
    for (ForwardIt i = begin; i != end; ++i)
        std::iter_swap(i, std::min_element(i, end));
}

三、插入排序

template<class ForwardIt>
void insertion_sort(ForwardIt begin, ForwardIt end)
{
    for (ForwardIt i = begin; i != end; ++i)
        std::rotate(std::upper_bound(v.begin(), i, *i), i, i+1);
}

四、归并排序

归并排序,详见1.5归并排序,有动图演示

template<class Iter>
void merge_sort(Iter first, Iter last)	
{
    if (last - first > 1) {
        Iter middle = first + (last - first) / 2;
        merge_sort(first, middle);
        merge_sort(middle, last);
        std::inplace_merge(first, middle, last);
    }
}

五、十大经典排序算法

https://www.runoob.com/w3cnote/ten-sorting-algorithm.html

你可能感兴趣的:(C++,c++,算法)