-
Notifications
You must be signed in to change notification settings - Fork 0
/
quicksort.cpp
69 lines (56 loc) · 1.24 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
@chiranjeevi
Date: 18-May-2017
#include <iostream>
#include <random>
#include <algorithm>
using namespace std;
void exchange(int arr[], int i, int j){
int temp=arr[i];
arr[i]=arr[j];
arr[j]=temp;
}
int partition(int arr[], int lo, int hi){
int i=lo,j=hi+1;
int pivot=lo;
while(true){
while(arr[++i]<arr[pivot]){ //most important step (for equal keys)
if(i>=hi)
break;
}
while(arr[--j]>arr[pivot]){ //cant decrement inside loop-creates problem for 1, 1, 1
if(j<=lo)
break;
}
if(i>=j)
break;
exchange(arr,i,j);
}
exchange(arr,pivot,j);
return j;
}
void quicksort(int arr[], int lo, int hi){
if(hi<=lo)
return;
int j=partition(arr,lo,hi);
quicksort(arr,lo,j-1);
quicksort(arr,j+1,hi);
}
void print(int arr[], int n){
for(int i=0; i<n; i++)
cout<<arr[i]<<" ";
cout<<endl;
}
int main() {
int n,range;
cin>>n>>range;
int arr[n];
default_random_engine gen;
uniform_int_distribution<int> dist(1,range);
for(int i=0; i<n; i++)
arr[i]=dist(gen);
random_shuffle(arr,arr+n);
print(arr,n);
quicksort(arr,0,n-1);
print(arr,n);
return 0;
}