-
Notifications
You must be signed in to change notification settings - Fork 492
/
QuickSort.cpp
76 lines (59 loc) Β· 1.12 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
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
/*------------------------QUICK SORT------------------------*/
/*Inventor: Tony Hoare
Worst complexity: n^2
Average complexity: n*log(n)
Best complexity: n*log(n)
Method: Partitioning
Stable: No
InPlace : YES
-----------------------------*/
#include <iostream>
#include<stack>
#include<map>
#include<bits/stdc++.h>
#include<string>
using namespace std;
void swap(int *a,int *b){
int temp=*a;
*a=*b;
*b=temp;
}
int partition(int *A,int low,int high){
int pivot=A[low];
int left=low,right=high;
while(left<right){
while(A[left]<=pivot && left<high){
left++;
}
while(right>low && A[right]>pivot){
right--;
}
if(left<right){
swap(&A[left],&A[right]);
}
}
swap(&A[low],&A[right]);
return right;
}
void Quick_sort(int *A,int low,int high){
if(low<high){ //More than one element -base condition
int p=partition(A,low,high);
Quick_sort(A,low,p-1);
Quick_sort(A,p+1,high);
}
}
void Print(int *A,int n){
for (int i = 0; i < n; i++)
cout << A[i] << " ";
}
int main(){
int n,no;
cin>>n;
int A[n];
for(int i=0;i<n;i++){
cin>>A[i];
}
Quick_sort(A,0,n-1);
Print(A,n);
return 0;
}