forked from Andyy-18/CPP-BASICS
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathR_quicksort.cpp
65 lines (57 loc) · 1.22 KB
/
R_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
#include<bits/stdc++.h>
using namespace std;
int partition(int arr[],int s,int e){
int pivot=arr[s];
int cnt=0;
for(int i=s+1;i<=e;i++){
if(arr[i]<=pivot){
cnt++;
}
}
//place pivot at right position
int pivotIndex=s+cnt;
swap(arr[pivotIndex],arr[s]);
//now left and right part
int i=s,j=e;
while(i<pivotIndex && j>pivotIndex){
while(arr[i]<pivot){
i++;
}
while(arr[i]>pivot){
j--;
}
if(i<pivotIndex && j>pivotIndex){
swap(arr[i++],arr[j--]);
}
}
return pivotIndex;
}
void quicksort(int arr[],int s,int e){
//base case
if(s>=e){
return;
}
//partition
int p=partition(arr,s,e);
//sorting left part
quicksort(arr,s,p-1);
//sorting right part
quicksort(arr,p+1,e);
}
int main()
{
int n;
cout<<"Enter the size : "<<endl;
cin>>n;
int arr[n];
cout<<"Enter your numbers : "<<endl;
for(int i = 0; i < n; i++){
cin>>arr[i];
}
quicksort(arr,0,n-1);
cout<<"sorted array: ";
for(int i=0;i<n;i++){
cout<<arr[i]<<" ";
}
return 0;
}