1 #include<iostream> 2 #include<vector> 3 #include<algorithm> 4 using namespace std; 5 void quick_sort(vector<int> & num,int left,int right) 6 { 7 if(left>=right)//如果递归到了尽头就直接返回 8 return; 9 int low=left; 10 int high=right; 11 int base=num[left];//选定最左边的为基准 12 while(low<high) 13 { 14 while(num[high]>=base&&low<high)//先从右向左找小于base的 15 { 16 high--; 17 } 18 num[low]=num[high]; 19 while(num[low]<=base&&low<high)//从左向右找第一个大于base的 20 { 21 low++; 22 } 23 num[high]=num[low]; 24 } 25 num[low]=base;//将基准放到high==low这个位置 26 quick_sort(num,left,low-1);//接下来递归下一层 27 quick_sort(num,high+1,right); 28 } 29 int main() 30 { 31 vector<int> num; 32 for(int i=1;i<=5;i++) 33 { 34 int t; 35 cin>>t; 36 num.push_back(t); 37 } 38 quick_sort(num,0,4); 39 for(auto &i:num) 40 cout<<i<<" "; 41 return 0; 42 }
快排就是一个分治的思想,将大于基准的放一边,小于的放一边,然后继续下一层