-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathQuickSort.cpp
66 lines (39 loc) · 977 Bytes
/
QuickSort.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
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
//Time complexity: O(nlogn)
// ARRAY METHOD
#include <bits/stdc++.h>
using namespace std;
int partition(int a[], int s, int e){
int i = s-1;
int pivot = a[e]; // set last element as pivot
for(int j=s; j<e; j++){ // for loop till one before end
if(a[j] < pivot){
i++; //increment and swap
swap(a[i],a[j]);
}
}
//Bring the pivot element in between Region 1 and 2
swap(a[i+1], a[e]); //swap the pivot with i+1
return i+1; //return pivot POSITION!! (not value!)
}
void quickSort( int a[], int s, int e){
if(s >=e){
return;
}
int p = partition(a,s,e);
quickSort(a, s, p-1); // sort left subarray
quickSort(a, p+1, e); // sort right subarray
}
int main(void){
int n;
int arr[100];
cin >> n;
for(int i=0; i<n; i++){
cin >> arr[i];
}
//call function
quickSort(arr,0,n-1);
for(int i=0; i<n; i++){
cout << arr[i] << " ";
}
return 0;
}