-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathInsertionSortADV.cpp
More file actions
95 lines (73 loc) · 1.26 KB
/
InsertionSortADV.cpp
File metadata and controls
95 lines (73 loc) · 1.26 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
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
// problem: "https://www.hackerrank.com/challenges/insertion-sort/problem"
#include<iostream>
#include<vector>
using namespace std;
long long int c = 0;
void mergeSort(vector<int>&A,int n)
{
int m = n/2;
if(m==0)
return;
int i;
vector<int>L;
for(i=0;i!=m;i++)
L.push_back(A[i]);
vector<int>R;
for(i=m;i!=n;i++)
R.push_back(A[i]);
// mergeSort L and R
mergeSort(L,m);
mergeSort(R,n-m);
// merge the two arrays
int j = 0,k = 0;
i = k = 0;
while(i<m && j<n-m)
{
if(L[i]<=R[j])
{
A[k] = L[i];
i++;
k++;
}
else
{ // if L[i]>R[j]
A[k] = R[j];
j++;
k++;
c = c+m-i;
}
}
while(i<m)
{
A[k] = L[i];
i++;
k++;
}
while(j<n-m)
{
A[k] = R[j];
j++;
k++;
}
}
int main()
{
int t;
cin>>t;
while(t--)
{
int n;
vector<int>A;
cin>>n;
int i,x;
for(i=0;i!=n;i++)
{
cin>>x;
A.push_back(x);
}
c = 0;
mergeSort(A,n); // define function
cout<<c<<'\n';
}
return 0;
}