-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy path10810 - Ultra-QuickSort.cpp
67 lines (58 loc) · 1014 Bytes
/
10810 - Ultra-QuickSort.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
#include<stdio.h>
#define inf 2000000000
#define sz 500005
void mergesort(int p,int r);
void merge(int p,int q,int r);
int a[sz],L[(sz/2)+5],R[(sz/2)+5];
long long int cnt;
int main()
{
int n,i;
while(scanf("%d",&n) && n)
{
for(i=1; i<=n; i++)
scanf("%d",&a[i]);
cnt=0;
mergesort(1,n);
printf("%lld\n",cnt);
}
return 0;
}
void mergesort(int p,int r)
{
if(p<r)
{
int q;
q=(p+r)/2;
mergesort(p,q);
mergesort(q+1,r);
merge(p,q,r);
}
return;
}
void merge(int p,int q,int r)
{
int ind1,ind2,k,i,j;
for(i=p,ind1=1; i<=q; i++)
L[ind1++]=a[i];
L[ind1]=inf;
for(i=q+1,ind2=1; i<=r; i++)
R[ind2++]=a[i];
R[ind2]=inf;
i=j=1;
for(k=p; k<=r; k++)
{
if(L[i]>R[j])
{
cnt+=ind1-i;
a[k]=R[j];
j++;
}
else
{
a[k]=L[i];
i++;
}
}
return ;
}