-
Notifications
You must be signed in to change notification settings - Fork 17
/
Copy pathQuickSort.cpp
53 lines (41 loc) · 1.06 KB
/
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
#include<iostream>
using namespace std;
int Partition(int a[],int start,int end){ // Function to find the index of the pivot element
int pivot = a[end]; // last element is chosen as pivot element
int pIndex= start;
for(int i = start;i<end;i++){
if(a[i]<=pivot){
swap(a[i],a[pIndex]);
pIndex++;
}
}
swap(a[pIndex],a[end]);
return pIndex; // returning the index of the pivot element
}
void Quick_Sort(int a[],int start,int end){
if(start<end){
int pivot = Partition(a,start,end); // The index of the pivot element is stored in variable pivot
Quick_Sort(a,start,pivot-1);
Quick_Sort(a,pivot+1,end);
}
}
int main(){
int n;
cin>>n;
int a[n];
for(int i = 0;i<n;i++){
cin>>a[i];
}
int start=0,end=n-1;
Quick_Sort(a,start,end);
for(int i = 0;i<n;i++){
cout<<a[i]<<" "; // displaying the sorted array
}
}
/*
Sample Input:
6
10 7 8 9 1 5
Sample Output:
1 5 7 8 9 10
*/