forked from PoeLoren/hackerrank
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathQuicksort In-Place.cpp
47 lines (44 loc) · 938 Bytes
/
Quicksort In-Place.cpp
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
43
44
45
46
47
#include <cmath>
#include <cstdio>
#include <vector>
#include <iostream>
#include <algorithm>
using namespace std;
int partition(vector<int>& a, int l, int r){
int key = a[r - 1];
int j = l - 1;
for(int i = l; i < r; ++i){
if(a[i] < key){
j++;
swap(a[i], a[j]);
}
}
j++;
swap(a[j], a[r-1]);
return j;
}
void quickSort(vector<int>& a, int l, int r){
if(r - l <= 1)
return ;
int p;
p = partition(a, l ,r);
cout << a[0];
for(int i = 1; i < a.size(); ++i)
cout << " " << a[i];
cout << endl;
quickSort(a, l, p);
quickSort(a, p + 1, r);
}
int main() {
/* Enter your code here. Read input from STDIN. Print output to STDOUT */
vector<int> a;
int n;
cin >> n;
for(int i = 0; i < n; ++i){
int num;
cin >> num;
a.push_back(num);
}
quickSort(a, 0, a.size());
return 0;
}