1 快速排序
分治法,在每一轮挑选一个基准元素,并让其他比它大的元素移到数动到数列一边,比它小的元素移动到数列的另一边,从而把数列拆解成两个部分。
快排的平均时间复杂度是O(nlogn)
1.1双边循环法
每次从右到左扫描high--,再从左到右扫描low++,交换arr[high]和arr[low]的位置
1.2单边循环法
如果记第一个元素arr[low]为pivot,定义一个mark指针初始化为low,循环从i从low+1向high遍历,一旦有元素小于基准值,那么mark++,并交换arr[mark] 与arr[i],这是因为mark移动没有i来得快,且指向的元素一定大于或者等于基准值,所以把小的往前移,最后的mark就是基准值应该放的位置
1.3输出每层递归
函数QuickSort加一个参数值deep,递归层为1时,也就是只有mark这一个元素在正确的位置上,
再往下进行递归,
#include<stdio.h>
#include<iostream>
using namespace std;
int res[1001];
// int a[1000]={0};
int quickSort(int *a, int low, int high, int deep){
if(low >= high)
return 0;
// if(low+1 == high)
if(low+1 == high){
if(a[low] > a[high])
swap(a[low],a[high]);
cout<<" == "<<endl;
return 0;
}
int mark = low;
int pivot = a[low];
for(int i=low; i<=high; i++){
if(a[i] < pivot){
mark++;
swap(a[mark],a[i]);
}
}
swap(a[low],a[mark]);
if(deep == 1){
res[mark] = a[mark];
cout<<"====1====="<<endl;
}
if(deep == 2){
for(int i=low; i<=high; i++){
res[i] = a[i];
}
cout<<"====2====="<<endl;
}
quickSort(a,low, mark-1,deep+1);
quickSort(a,mark+1,high,deep+1);
return 0 ;
}
int main(){
int n;cin>>n;
cin.clear();
for(int i=0; i <n; i++){
int num;cin>>num;
int a[1000] = {0};
for(int j=0; j <num; j++)
cin>>a[j];
int d = quickSort(a,0,num-1,1);
for(int j=0; j <num; j++)
cout<<res[j]<<" ";
cout<<endl;
}
}