-
Notifications
You must be signed in to change notification settings - Fork 1
/
Inversion_Mege_Sort_Enhance.cpp
65 lines (56 loc) · 1.17 KB
/
Inversion_Mege_Sort_Enhance.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
#include<iostream>
using namespace std;
int merge_sort(int a,int n);
int merg(int a[],int b[],int lb,int mid,int ub);
int mergesort(int a[],int temp[],int lb,int ub);
int merg(int a[],int b[],int lb,int mid,int ub)
{
int i=lb,j=mid+1,k=lb,inv=0;
while(i<=mid&&j<=ub)
{
if(a[i]<=a[j])
{
b[k++]=a[i++];
}
else
{
b[k++]=a[j++];
inv=inv+(mid-i);
}
}
while(j<=ub)
{
b[k++]=a[j++];
}
while(i<=mid)
{
b[k++]=a[i++];
}
for(k=lb;k<=ub;k++)
a[k]=b[k];
return inv;
}
int mergesort(int a[],int temp[],int lb,int ub)
{
int inv=0;
if(lb<ub)
{
int mid=(lb+ub)/2;
inv+=mergesort(a,temp,lb,mid);
inv+=mergesort(a,temp,mid+1,ub);
inv+=merg(a,temp,lb,mid,ub);
}
return inv;
}
int merge_sort(int a[],int n)
{
int temp[n];
return mergesort(a,temp,0,n-1);
}
int main()
{
int a[]{1, 20, 6, 4, 5},i;
int n=sizeof(a)/sizeof(a[0]);
int inv= merge_sort(a,n);
cout<<inv;
}