-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathw_4_2.cpp
More file actions
70 lines (57 loc) · 1.7 KB
/
Copy pathw_4_2.cpp
File metadata and controls
70 lines (57 loc) · 1.7 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
62
63
64
65
66
67
68
69
70
#include<bits/stdc++.h>
using namespace std;
int partition(vector<int>& arr, int lb, int rb, int &cmp, int &swp) {
srand(time(0)); // Seed the random number generator
// Select a random index for the pivot
int pid = rand() % (rb - lb + 1) + lb;
int pivot = arr[pid];
// Swap pivot with the first element (so it will be in the right place later)
swap(arr[lb], arr[pid]);
swp++;
int s = lb + 1; // Start pointer
int e = rb; // End pointer
while (s <= e) {
while (s <= rb && arr[s] <= pivot) {
cmp++;
s++;
}
// Move the end pointer to the left until we find an element smaller than the pivot
while (e >= lb && arr[e] > pivot) {
cmp++;
e--;
}
// If start pointer is still less than end pointer, swap elements
if (s < e) {
swap(arr[s], arr[e]);
swp++;
}
}
// Swap the pivot into its correct position
swap(arr[lb], arr[e]);
swp++;
return e; // Return the pivot index
}
void quick_sort(vector<int>&arr,int s,int e,int &cmp,int &swp){
if(s >= e)return;
int part = partition(arr,s,e,cmp,swp);
quick_sort(arr,s,part-1,cmp,swp);
quick_sort(arr,part+1,e,cmp,swp);
}
int main(){
int n;
cout<<"enter size of array:"<<endl;
cin>>n;;
vector<int>arr(n);
for(int i=0;i<n;i++){
cin>>arr[i];
}
int cmp = 0,swp = 0;
quick_sort(arr,0,n-1,cmp,swp);
cout<<"sorted array is"<<endl;
for(int i=0;i<n;i++){
cout<<arr[i]<<" ";
}
cout<<"number of comparisons: "<<cmp<<endl;
cout<<"total no of swaps are:"<<swp<<endl;
return 0;
}