好多年前学习的知识,最近面试有点忘记了。复习一下。
简单的说:
1.partition只做位置划分,不做递归
2.while找右边不合法数,交换,然后找左边不合法数,交换。
#include <iostream>
#include <vector>
using namespace std;
int partition(vector<int> &r,int s,int e);
void print(vector<int> &r){
for(int i=0;i<r.size();i++){
std::cout<<r[i]<<" ";
}
std::cout<<std::endl;
}
void qiuck_sort(vector<int> &r,int s,int e){
if(s<e){
int mid = partition(r,s,e);
qiuck_sort(r,s,mid-1);
qiuck_sort(r,mid+1,e);
}
}
int partition(vector<int> &r,int s,int e){
int v = r[s];
while(s<e){
while(s<e && r[e]>=v){
e--;
}
r[s] = r[e];
while(s<e && r[s]<=v){
s++;
}
r[e] = r[s];
}
r[s] = v;
return s;
}
int main(){
vector<int>r = {-1,4,-9,2,6,3,7};
print(r);
qiuck_sort(r,0,r.size()-1);
print(r);
}