明天要面试,听说会考快速排序,预习一下
/*
选在一个基准数,比它小的在它的左边,比它大的在它的右边。(分治)
然后再对左右两部分进行上面的操作一直到最后
时间复杂度O(n^2)到O(nlogn)
不是稳定的排序方式
*/
#include<bits/stdc++.h>
using namespace std;
void QuickSOrt(int a[], int start, int last){
if(start>=last) return ;
int i = start;
int j = last;
int temp = a[i];
while(i<j){
while(i<j && a[j]>=temp)
j--;
if(i<j){
a[i] = a[j];
i++;
}
while(i<j && temp>a[i])
i++;
if(i<j){
a[j] = a[i];
j--;
}
}
a[i] = temp;//把基准数放到i的位置;
QuickSOrt(a,start,i-1);
QuickSOrt(a,i+1,last);
}
int main(){
// freopen("../out.txt","w",stdout);
const int NUM = 10;
int a[NUM] = {0};
srand(time(0));
for(int i=0;i<NUM;++i)
a[i] = 1+rand()%100;
for(int i=0;i<NUM;++i)
cout<<a[i]<<" ";
cout<<endl;
QuickSOrt(a,0,NUM-1);
for(int i=0;i<NUM;++i)
cout<<a[i]<<" ";
cout<<endl;
return 0;
}