Quicksort

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
#include<stdio.h>
#include<stdlib.h>
#include<iostream>
#include<algorithm>
#define N 1000000
 
using namespace std;
 
int a[N];
 
void quicksort(int x[], int left, int right)
{
    if(left >= right)return;
    int i = left;
    int j = right;
    swap(x[i], x[(rand() % (right - left + 1)) + left]);
    int key = x[i];
    while(i < j){
        while(i < j && x[j] >= key)j--;
        if(i < j)swap(x[i++], x[j]);
        while(i < j && x[i] <= key)i++;
        if(i < j)swap(x[i], x[j--]);
    }
    quicksort(x, left, i - 1);
    quicksort(x, i + 1, right);
}
 
int main()
{
    int n;
    while(~scanf("%d", &n)){
        for(int i = 0; i < n; i++){
            cin >> a[i];
        }
        quicksort(a, 0, n - 1);
        for(int i = 0; i < n; i++){
            cout << a[i] << ' ';
        }
        cout << endl;
    }
    return 0;
}

  

posted @   lemadmax  阅读(179)  评论(0编辑  收藏  举报
点击右上角即可分享
微信分享提示