转载请注明出处。
快速排序采用的思想是分治思想。分治算法的基本思想是将一个规模为N的问题分解为K个规模较小的子问题,这些子问题相互独立且与原问题性质相同。求出子问题的解,就可以得到原问题的解。下面这张图会说明分治算法是如何进行的:将cn分成了两个cn/2,转而分成了cn/4,cn/8......我们通过这样一层一层的求解规模小的子问题,将其合并之后就能求出原问题的解。
假设升序排列n个元素。
1、选择一个元素作为pivot,比pivot小的移到左边,大的移到右边,将序列分为两部分,是不稳定的排序算法。
2、对两个子序列递归执行步骤1。
算法:前后指针法
一个指针指示界限,另一个指针遍历序列。
时间复杂度:
Number of comparisons | Number of swaps | |
---|---|---|
平均 | ||
最坏 |
测试代码:
#include<iostream>
#include<iterator>
using namespace std;
void swap(int &lhs, int &rhs)
{
int temp(lhs);
lhs = rhs;
rhs = temp;
}
int partition(int list[], int begin, int end)
{
int boundary(begin), i(begin+1);
for(; i<=end; i++)
{
if(list[i] < list[begin])
{
boundary++;
swap(list[boundary], list[i]);
}
}
swap(list[begin], list[boundary]);
return boundary;
}
void quickSort(int list[], int begin, int end)//recursion; ascend
{
if(end > begin)
{
int pivotIndex( partition(list, begin, end) );
quickSort(list, begin, pivotIndex-1);
quickSort(list, pivotIndex+1, end);
}
}
int main()
{
ostream_iterator<int> screen(cout, ", ");
int list[] = { 18, 8, 11, 9, 15, 20, 32, 61, 22, 48, 75, 83, 35, 3 };
quickSort(list, 0, 13);
copy(list, list + sizeof(list)/sizeof(int), screen);
cout << endl;
return 0;
}
参考资料:
百度百科,https://baike.baidu.com/item/快速排序算法/369842?fromtitle=快速排序&fromid=2084344&fr=aladdin
快速排序,https://blog.youkuaiyun.com/Payshent/article/details/60879120