快速排序是对冒泡排序的一种改进。思想:通过一趟排序将要排序的数据分割成独立的两部分,其中一部分的所有数据都比另外一部分的所有数据都要小,
然后再按此方法对这两部分数据分别进行快速排序,整个排序过程可以递归进行,以此达到整个数据变成有序。
选择一个基准数,这个数的左边都比她小,右边的都比它大,然后再递归处理左右两边的操作直到左右的各区只有一个数
数组: 3,2,1,6,9
#include <iostream>
using namespace std;
void Qsort(int a[], int low, int high)
{
if (low >= high)
return;
int frist = low;
int last = high;
int key = a[frist];
while (frist < last)
{
while (frist < last &&a[last] > key)
--last;
a[frist] = a[last];
while (frist < last && a[frist] < key)
++frist;
a[last] = a[frist];
}
a[frist] = key;
Qsort(a, low, frist);
Qsort(a, frist + 1,high);
}
int main()
{
int a[] = {3,1,2,6,9};
Qsort(a,0 sizeof(a)/4 -1);
for(int i = 0;i< sizeof(a)/4;i++)
printf("%d ",a[i]);
}
当数据有序时,以第一个关键字为基准分为两个子序列,前一个子序列为空,此时执行效率最差。O(N2)
而当数据随机分布时,以第一个关键字为基准分为两个子序列,两个子序列的元素个数接近相等,此时执行效率最好O(Nlog2N)
快速排序在每次分割的过程中,需要 1 个空间存储基准值。而快速排序的大概需要 Nlog2N次 的分割处理,所以占用空间也是Nlog2N 个。
不稳定
来源:https://www.cnblogs.com/xiaoma123/p/5220492.html