Repository navigation
Expand file tree
/
Copy pathquicksort.cpp
More file actions
79 lines (71 loc) · 1.39 KB
/
Copy pathquicksort.cpp
File metadata and controls
79 lines (71 loc) · 1.39 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
71
72
73
74
75
76
77
78
#include<iostream>
using namespace std;
int comparisons=0;
int swaps=0;
int totc=0;
int tots=0;
int n=0;
int partition(int A[], int p, int r)
{
int x,j,i,temp,k;
x=A[r];
cout<<"\nPivot selected = "<<x<<endl;
i=p-1;
for(int j=p; j<=r-1; j++)
{
comparisons++;
if(A[j] < x)
{
i=i+1;
temp=A[i];
A[i]=A[j];
A[j]=temp;
swaps++;
}
}
temp=A[i+1];
A[i+1]=A[r];
A[r]=temp;
swaps++;
cout<<"\nIntermediate Array:\n";
for(k=0; k<n; k++)
{
cout<<A[k]<<" ";
}
cout<<"\nNumber of comparisons = "<<comparisons;
cout<<"\nNumber of swaps = "<<swaps<<endl;
totc+=comparisons;
tots+=swaps;
return (i+1);
}
void quicksort(int A[], int p, int r)
{
int q;
if(p < r)
{
q=partition(A,p,r); //q represents sorted position
quicksort(A,p,q-1);
quicksort(A,q+1,r);
}
}
int main()
{
int i;
cout<<"Enter number of elements:\t";
cin>>n;
int A[n];
cout<<"\nEnter elements for sorting:\n";
for(i=0; i<n; i++)
{
cin>>A[i];
}
quicksort(A,0,n-1);
cout<<"\n\nSorted Array is:\n";
for(i=0; i<n; i++)
{
cout<<A[i]<<" ";
}
cout<<"\n\nTotal number of comparisons = "<<totc;
cout<<"\nTotal number of swaps = "<<tots;
return 0;
}