-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathQuick_Sort.cpp
More file actions
72 lines (53 loc) · 1002 Bytes
/
Quick_Sort.cpp
File metadata and controls
72 lines (53 loc) · 1002 Bytes
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
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
#include <bits/stdc++.h>
using namespace std;
int partition(vector<int>& a, int l, int r)
{
int random=l + rand() % (r - l);
swap(a[l], a[random]);
int pivot = a[l];
int count = 0;
for (int i = l + 1; i <= r; i++) {
if (a[i] <= pivot)
count++;
}
int pivotIndex = l + count;
swap(a[pivotIndex], a[l]);
int i = l, j = r;
while (i < pivotIndex && j > pivotIndex) {
while (a[i] <= pivot) {
i++;
}
while (a[j] > pivot) {
j--;
}
if (i < pivotIndex && j > pivotIndex) {
swap(a[i], a[j]);
i++, j--;
}
}
return pivotIndex;
}
void quick_sort_array(vector<int> &a,int l, int r)
{
if (l<r){
int p = partition(a, l, r);
quick_sort_array(a, l, p - 1);
quick_sort_array(a, p + 1, r);
}
return;
}
int main()
{
int n;
cin>>n;
vector<int> a(n);
for(int i=0;i<n;i++){
cin>>a[i];
}
quick_sort_array(a, 0, n-1);
for(int i=0;i<n;i++){
cout<<a[i]<<" ";
}
cout<<endl;
return 0;
}