在acwing找的算法,优化了空间复杂度,包容性更强,比赛适合使用,而且好记。
void QuickSort(int a[], int low, int high){
if(low>=high) return;
int i=low-1;//扩
int j=high+1;
int x=a[low+high>>1];//x取数组最中间的值,对比其他快排更优化内存,其他的快排是取第一个
while (i<j){
do i++; while (a[i]<x);//从左往右,到比x大的为止
do j--; while (a[j]>x);//从右往左,到比x小的为止
if(i<j) swap(a[i],a[j]);//交换:因为要把左边的比x大的值换到x的右边,右边同理把小的换到左边,让数组呈现升序的排列,降序反之。
}
//递归
QuickSort(a,low,j);
QuickSort(a,j+1,high);
}
全部代码:
#include <iostream>
#include <algorithm>//sort函数,也很快,非必要我就用sort(a,a+n)的函数
using namespace std;
void QuickSort(int a[], int low, int high);
int main()
{
int n;
cin>>n;
int a[n];
for(int i=0;i<n;i++)
cin>>a[i];
//sort(a,a+n);
QuickSort(a,0,n-1);
for(int i=0;i<n;i++){
if(i!=n-1)cout<<a[i]<<" ";
else cout<<a[i];
}
}
void QuickSort(int a[], int low, int high){
if(low>=high) return;
int i=low-1,j=high+1,x=a[low+high>>1];
while (i<j){
do i++; while (a[i]<x);
do j--; while (a[j]>x);
if(i<j) swap(a[i],a[j]);
}
QuickSort(a,low,j);
QuickSort(a,j+1,high);
}