-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path1_Randomized_QuickSort.cpp
More file actions
61 lines (47 loc) · 1.04 KB
/
1_Randomized_QuickSort.cpp
File metadata and controls
61 lines (47 loc) · 1.04 KB
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
#include <bits/stdc++.h>
using namespace std;
int partition(int arr[], int p, int r, int &count)
{
int i=p-1, j=p, pivot=arr[r];
for(j=p; j<=r-1; j++)
{
count++;
if(arr[j]<pivot)
{
i++;
swap(arr[i], arr[j]);
}
}
swap(arr[i+1], arr[r]);
return i+1;
}
int randomized_partition(int arr[], int p, int r, int &count)
{
srand(time(0));
int random = p+rand()%(r-p+1);
swap(arr[r], arr[random]);
return partition(arr, p, r, count);
}
void quick_sort(int arr[], int p, int r, int &count)
{
if(p<r)
{
int q=randomized_partition(arr, p, r, count);
quick_sort(arr, p, q-1, count);
quick_sort(arr, q+1, r, count);
}
}
int main() {
int count=0;
int n;
cin>>n;
int arr[n];
for(int i=0;i<n;i++){
cin>>arr[i];
}
quick_sort(arr, 0, n-1, count);
cout << "No. of comparisons : " << count << endl;
for(int i=0; i<n; i++)
cout << arr[i] << " ";
return 0;
}