这章介绍了应用广泛的快速排序算法。 快速排序的最坏性能是O(n*n), 但是平均性能 却不错,而且系数较小。 故而被广泛使用。 因为快速排序本身很简单, 所以本章的重点在于算法性能的分析。 算法性能并不是本次算法学习的重心, 所以只是读了证明, 习题中的算法性能分析部分只是略略看过, 以后各章的性能分析恐怕也不能花太多功夫, 毕竟不是在求学阶段, 太过基础的东西,很难静下心来慢慢看过了, 实用意义可能也不是足够的大。 如上。 实现的快速排序如下:
template<class Iter, class Function>
Iter partition(Iter first, Iter last, Function f)
{
Iter back = last - 1;
Iter it = first;
for (Iter it2 = first; it2 != back; ++it2)
{
if (f(*it2, *back))
{
std::swap(*it, *it2);
++it;
}
}
std::swap(*it, *back);
return it;
}
template<class Iter, class Function>
void quickSort(Iter first, Iter last, Function f)
{
if (last - first > 10)
{
Iter middle = partition(first, last, f);
quickSort(first, middle, f);
quickSort(middle + 1, last, f);
}
else
{
insertionSort(first, last, f);
}
}
当序列中的数据小于10的时候,应用插入排序, 其它没有变化。