Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
afnan47
GitHub Repository: afnan47/sem7
Path: blob/main/DAA/6_QuickSort.cpp
418 views
1
#include<iostream>
2
3
using namespace std;
4
5
int partition(int * arr, int p, int r){
6
int x = arr[r];
7
int i = p - 1;
8
for(int j = p; j < r; j++){
9
if(arr[j] <= x){
10
i++;
11
swap(arr[i],arr[j]);
12
}
13
}
14
swap(arr[i + 1], arr[r]);
15
return i + 1;
16
}
17
18
void quickSort(int * arr, int p, int r){
19
if (p < r){
20
int q = partition(arr, p, r);
21
quickSort(arr, p, q - 1);
22
quickSort(arr, q + 1, r);
23
}
24
}
25
26
//Randomized
27
int randomPartition(int * arr, int p, int r){
28
int x = arr[r];
29
int i = rand() % ((r - p) + 1) + p;
30
cout << i << endl;
31
for(int j = p; j < r; j++){
32
if(arr[j] <= x){
33
i++;
34
swap(arr[i],arr[j]);
35
}
36
}
37
swap(arr[i + 1], arr[r]);
38
return i + 1;
39
}
40
41
void radomizedQuickSort(int * arr, int p, int r){
42
if (p < r){
43
int q = randomPartition(arr, p, r);
44
radomizedQuickSort(arr, p, q - 1);
45
radomizedQuickSort(arr, q + 1, r);
46
}
47
}
48
49
int main(){
50
int A[] = {23,34,54,123,34,56,67676,112};
51
int n = sizeof(A)/ sizeof(A[0]);
52
radomizedQuickSort(A, 0, n - 1);
53
for(int i : A){
54
cout << i << " ";
55
}
56
cout << '\n';
57
return 0;
58
}
59