Skip to content

Commit 160d494

Browse files
Added Quick Sort and Randomized Quick Sort
I've also explained why randomized quick sort is better.
1 parent 2b73a76 commit 160d494

File tree

1 file changed

+44
-0
lines changed

1 file changed

+44
-0
lines changed
Lines changed: 44 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,44 @@
1+
#include<bits/stdc++.h>
2+
using namespace std;
3+
4+
int partition(int A[],int s,int e){
5+
int pivot=A[e];
6+
int pindx=s;
7+
for(int i=s;i<=e-1;i++){
8+
if(A[i]<=pivot){
9+
swap(A[i],A[pindx]);
10+
pindx++;
11+
}
12+
}
13+
swap(A[pindx],A[e]);
14+
return pindx;
15+
}
16+
17+
int randompartition(int A[],int s,int e){
18+
int pindx = (rand() %(e - s + 1)) + s;
19+
swap(A[pindx],A[e]);
20+
return partition(A,s,e);
21+
}
22+
23+
void quickSort(int *A,int s,int e){
24+
if(s>=e)
25+
return;
26+
int pindx=randompartition(A,s,e);
27+
quickSort(A,s,pindx-1);
28+
quickSort(A,pindx+1,e);
29+
}
30+
31+
int main(){
32+
int A[]={5,2,7,11,-3,4,66,12};
33+
int n=sizeof(A)/sizeof(A[0]);
34+
//-3,2,4,5,7,11,12,66
35+
quickSort(A,0,n-1);
36+
37+
for(int i=0;i<n;i++)
38+
cout<<A[i]<<" ";
39+
}
40+
41+
/*NOTE: Randomized Partition is always recommended because if by chance extreme element (minimum or maximum)
42+
is selected then time complexity will be worst aka O(n^2), Randomized partition increases the probability
43+
such that non extreme element is selected as pivot this will result in time complexity of O(nlogn), which is
44+
far better than O(n^2).*/

0 commit comments

Comments
 (0)