在浏览Wikipedia's list of sorting algorithms时,我注意到没有O(n*log(n))
(最坏情况)时间复杂度和O(1)
(最坏情况)空间的稳定comparison sort - 复杂。这肯定看起来像一个理论界限,但我找不到更多关于它的信息。
如何证明这一点?
注意:我知道比较排序的O(n*log(n))
最坏情况时间复杂度的下限。
答案 0 :(得分:8)
尽管那篇文章说的是in-place stable Merge Sort can be made O(n log n)
。
Here是一篇论文,解释了实现它的两种方法。
答案 1 :(得分:0)
#include <algorithm>
#include <functional>
template<class It>
It rotate(It begin, It const middle, It end)
{
typename std::iterator_traits<It>::difference_type i = 0, j;
if (begin != middle && middle != end)
{
while ((i = std::distance(begin, middle)) !=
(j = std::distance(middle, end)))
{
It k = middle;
std::advance(
k,
std::max(
typename std::iterator_traits<It>::difference_type(),
j - i));
std::swap_ranges(k, end, begin);
if (i > j) { std::advance(begin, j); }
else { std::advance(end, -i); }
}
}
return std::swap_ranges(middle - i, middle, middle);
}
template<class It, class Less>
It bsearch(
It begin, It left, It right,
typename std::iterator_traits<It>::difference_type n,
Less &less)
{
while (left < right)
{
It const middle = left + std::distance(left, right) / 2;
bool const b = !less(
*(begin + (std::distance(middle, begin) + n)),
*middle);
(b ? left : right) = middle + b;
}
return left;
}
template<class It, class Less>
void merge(It const begin, It const middle, It const end, Less &less)
{
bool naive_insertion_optimization = false;
if (naive_insertion_optimization && std::distance(begin, end) < 0)
{
for (It i = middle; i != end; ++i)
{
for (It p = i; p != begin; --p)
{
if (!less(*p, *(p - 1)))
{
break;
}
using std::iter_swap;
iter_swap(p, p - 1);
}
}
}
else if (begin < middle && middle < end)
{
typename std::iterator_traits<It>::difference_type const
half = std::distance(begin, end) / 2,
left = std::distance(begin, middle),
right = std::distance(middle, end);
It const midpoint = begin + half;
bool const b = left > right;
It const i = bsearch(
begin,
b ? midpoint - right : begin,
b ? midpoint : middle,
half + left - 1,
less);
rotate(i, middle, begin + (std::distance(i, middle) + half));
merge(begin, i, midpoint, less);
merge(midpoint, midpoint + std::distance(i, middle), end, less);
}
}
template<class It, class Less>
void sort(It const begin, It const end, Less &less)
{
if (std::distance(begin, end) > 1)
{
It const middle = begin + std::distance(begin, end) / 2;
sort(begin, middle, less);
sort(middle, end, less);
merge(begin, middle, end, less);
}
}
template<class It>
void sort(It const begin, It const end)
{
std::less<typename std::iterator_traits<It>::value_type> less;
return sort(begin, end, less);
}