-
Notifications
You must be signed in to change notification settings - Fork 0
/
Count Inversions.cpp
66 lines (61 loc) · 1.09 KB
/
Count Inversions.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
#include<stdio.h>
#include<conio.h>
int count = 0;
void merge(int array[], int begin,int mid,int end)
{
int i=begin,j=mid+1,index=begin,k=0,temp[100];
while (i<=mid && j<=end)
{
if (array[i]<=array[j])
{
temp[index]=array[i];
i++;
}
else
{
count += (mid-i+1);
temp[index]=array[j];
j++;
}
index++;
}
while(j<=end)
{
temp[index]=array[j];
j++;
index++;
}
while(i<=mid)
{
temp[index]=array[i];
i++;
index++;
}
for (k=begin;k<=end;k++)
{
array[k]=temp[k];
}
}
void mergesort(int array[], int begin, int end)
{
if (begin<end)
{
int mid = (begin+end)/2;
mergesort(array,begin,mid);
mergesort(array,mid+1,end);
merge(array,begin,mid,end);
}
}
int main()
{
int i,n;
scanf("%d",&n);
int a[n];
for (i=0;i<n;i++)
scanf("%d",&a[i]);
mergesort(a,0,n-1);
for (i=0;i<n;i++)
printf("%d ",a[i]);
printf("\nInversions: %d",count);
return 0;
}