快速排序模板

 1 #include <iostream>
 2 #include <vector>
 3 #include <algorithm>
 4 #include <string>
 5 #include <cstdio>
 6 using namespace std;
 7 int a[100010];
 8 /*
 9 void quick_sort(int *a,int left,int right){
10     if(left>=right)return;
11     int i = left;
12     int j = right;
13     int key = a[left];
14     while(i<j){
15         while(i<j&&a[j]>=key)j--;
16         a[i] = a[j];
17         while(i<j&&a[i]<=key)i++;
18         a[j] = a[i];
19     }
20     a[i] = key;
21     quick_sort(a,left,i-1);
22     quick_sort(a,i+1,right);
23 }
24 */
25 void quick_sort(int *a,int l,int r){
26     if(l>=r)return;
27     int i = l, j = r, key = a[l];
28     while(i<j){
29         while(i<j&&a[j]>=key)j--;
30         a[i] = a[j];
31         while(i<j&&a[i]<=key)i++;
32         a[j] = a[i];
33     }
34     a[i] = key;
35     quick_sort(a,l,i-1);
36     quick_sort(a,i+1,r);
37 }
38 int main()
39 {
40     int n;
41     scanf("%d",&n);
42     for(int i = 0; i < n; i++)scanf("%d",&a[i]);
43     quick_sort(a,0,n-1);
44     for(int i = 0; i < n; i++)
45         printf("%d ",a[i]);
46     return 0;
47 }
相關文章
相關標籤/搜索