-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathquick_sort.cpp
More file actions
56 lines (51 loc) · 951 Bytes
/
quick_sort.cpp
File metadata and controls
56 lines (51 loc) · 951 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
#include <iostream>
#include <bits/stdc++.h>
using namespace std;
/*
1.Divide and conquer algorithm
2. NlogN average case.
3. N^2 worst case.
4. Fixed by Randomized quicksort
5. Inplace algorithm
*/
int partition(vector<int> &arr,int s,int e){
//In place (Cant take extra array)
int i = s-1;
int j = s;
int pivot = arr[e];
for(;j<=e-1;){
if(arr[j] <= pivot){
//merge the smaller element in the region-1
i = i + 1;
swap(arr[i],arr[j]);
}
//expand the larger region
j = j + 1;
}
swap(arr[i+1],arr[e]);
return (i + 1);
}
void quicksort(vector<int> &arr,int s,int e){
//Base case
if(s>=e)
return;
//Recusive Case
int pivot = partition(arr,s,e);
//left part
quicksort(arr,s,pivot - 1);
//right part
quicksort(arr,pivot + 1,e);
}
int main(){
int n;
cin>>n;
vector<int> vec;
for(int i=0;i<n;i++){
int t;
cin>>t;
vec.push_back(t);
}
quicksort(vec,0,n-1);
for(int i=0;i<n;i++)
cout<<vec[i]<<" ";
}