快速排序
快速排序算法复杂度
快速排序的平均时间复杂度为O(n×log(n)),最糟糕时复杂度为O(n^2)
算法稳定性
不稳定。
c++ 实现代码
#include<iostream>
using namespace std;
void QuickSort(int* a, int low, int high);
int Partition(int* a, int low, int high);
int main()
{
//int a[10] = {1,3,2,7,8,5,4,9,6,0};
int a[10] = {1,2,3,4,5,6,7,8,9,0};
int len = sizeof(a)/sizeof(a[0]);
QuickSort(a,0,9);
cout<<"after:"<<endl;
for(int i=0;i<len;i++)
{
cout<<a[i]<<" ";
}
return 0;
}
void QuickSort(int* a, int low, int high)
{
if (low < high)
{
int q = Partition(a, low, high);
for(int i=0;i<10;i++)
{
cout<<a[i]<<" ";
}
cout<<endl;
QuickSort(a, low, q - 1);
QuickSort(a, q + 1, high);
}
}
int Partition(int* a, int low, int high)
{
int x = a[high];//将输入数组的最后一个数作为主元,用它来对数组进行划分
int i = low - 1;
for (int j = low; j < high; j++) //遍历下标由low到high-1的数
{
if (a[j] < x)//如果数小于主元的话就将i向前挪动一个位置,并且交换j和i所分别指向的数
{
int temp;
i++;
temp = a[i];
a[i] = a[j];
a[j] = temp;
}
}
//经历上面的循环之后下标为从low到i(包括i)的数就均为小于x的数了,现在将主元和i+1位置上面的数进行交换
a[high] = a[i + 1];
a[i + 1] = x;
return i + 1;
}