-
Notifications
You must be signed in to change notification settings - Fork 1
/
2A.cpp
120 lines (87 loc) · 1.54 KB
/
2A.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
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
#include<bits/stdc++.h>
using namespace std;
typedef long long int ll;
int medianOfThree(ll a[], int l, int r)
{
int n = (r-l+1);
int mid_index = n/2 - (n%2==0 ? 1 : 0);
int mid = l+mid_index;
int x=a[l], y=a[r], z=a[mid];
int minn=min(min(x, y), z), maxx=max(max(x, y), z);
if(x > minn && x < maxx)
return l;
if(y > minn && y < maxx)
return r;
if(z > minn && z < maxx)
return mid;
}
int getPivot(ll a[], int l, int r, int mode)
{
switch(mode)
{
case 0: return l;
case 1: return r;
case 2: return medianOfThree(a, l, r);
}
}
int partitionR(ll a[], int l, int r, int pivot, ll &ct)
{
swap(a[r], a[pivot]);
ct = ct + (ll) (r-l+1-1);
int i=l-1, j=l;
for(;j<r;j++)
{
if(a[j] < a[r])
{
i++;
swap(a[i], a[j]);
}
}
i++;
swap(a[i], a[r]);
return i;
}
int partitionL(ll a[], int l, int r, int pivot, ll &ct)
{
swap(a[l], a[pivot]);
ct = ct + (ll) (r-l+1-1);
int i=l, j=l+1;
for(;j<=r;j++)
{
if(a[j] < a[l])
{
i++;
swap(a[i], a[j]);
}
}
swap(a[i], a[l]);
return i;
}
void quickSort(ll a[], int l, int r, int mode, ll &ct)
{
if(l>=r)
return;
int pivot = getPivot(a, l, r, mode);
int p = partitionL(a, l, r, pivot, ct);
quickSort(a, l, p-1, mode, ct);
quickSort(a, p+1, r, mode, ct);
}
void printArr(ll a[], int l, int r)
{
while(l<=r)
cout<<a[l++]<<" ";
cout<<endl;
}
int main()
{
ll n = 10000;
freopen("QuickSort.txt", "r", stdin);
ll a[10001]={0};
for(int i=0;i<n;i++)
cin>>a[i];
ll ct=0;
quickSort(a, 0, n-1, 2, ct);
printArr(a, 0, n-1);
cout<<ct<<endl;
return 0;
}