Skip to content

Commit 9d72abe

Browse files
authored
Merge pull request #87 from soumya997/soumyadip1
added quick sort using c++
2 parents f1796ba + c97fe1b commit 9d72abe

File tree

1 file changed

+68
-0
lines changed

1 file changed

+68
-0
lines changed
Lines changed: 68 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,68 @@
1+
// Quick Sort using c++
2+
#include <iostream>
3+
using namespace std;
4+
5+
/*
6+
Here's what is happening,
7+
we are selecting an element as a pivot element, and based on that
8+
we are dividing the array by two parts, 1st part is having elements
9+
lesser and equal to(<=) the pivot element and 2nd part having elements consists
10+
of larger(>) than the pivot element. After that, we simply sort the two parts
11+
recursively.
12+
13+
Now, the dividing part is done by the partition function and the sorting
14+
part via the quickSort function.
15+
16+
average time complexity- NlogN
17+
worst time complexity - N^2
18+
Approach- Divide and Conquer
19+
*/
20+
21+
22+
23+
int partition(int *arr,int s,int e){
24+
int i=s-1;
25+
int j=s;
26+
int pivot=arr[e];
27+
for(;j<=e-1;j++){
28+
if(arr[j]<=pivot){
29+
i=i+1;
30+
swap(arr[i],arr[j]);
31+
}
32+
33+
}
34+
swap(arr[i+1],arr[e]);
35+
return i+1;
36+
}
37+
38+
39+
void quickSort(int *arr,int s,int e){
40+
// base case
41+
if(s>=e){
42+
return;
43+
}
44+
// rec-case
45+
int p = partition(arr,s,e);
46+
quickSort(arr,s,p-1);
47+
quickSort(arr,p+1,e);
48+
}
49+
50+
51+
int main() {
52+
int n;
53+
cin>>n;
54+
int arr[n];
55+
56+
for(int i=0;i<n;i++){
57+
cin>>arr[i];
58+
}
59+
// functin call
60+
quickSort(arr,0,n-1);
61+
62+
cout<<"After Quick Sort: ";
63+
for(int i=0;i<n;i++){
64+
65+
cout<<arr[i]<<" ";
66+
}
67+
}
68+

0 commit comments

Comments
 (0)