[Hacker Rank] Insertion Sort Advanced Analysis

Insertion Sort Advanced Analysis

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
#include <bits/stdc++.h>

using namespace std;

/*
* Complete the 'insertionSort' function below.
*
* The function is expected to return an INTEGER.
* The function accepts INTEGER_ARRAY arr as parameter.
*/
int fenwick[10000001];
int qry(int n) {
int res = 0;
while(n > 0) {
res += fenwick[n];
n -= n & -n;
}
return res;
}
void update(int n) {
while(n < 10000001) {
fenwick[n] += 1;
n += n & -n;
}
}
long insertionSort(vector<int>& arr) {
memset(fenwick, 0, sizeof(fenwick));
long res = 0, n = arr.size();
update(arr[0]);
for(int i = 1; i < n; i++) {
res += i - qry(arr[i]);
update(arr[i]);
}
return res;
}

int main()
{
int tc, n;
cin>>tc;
while(tc--) {
cin>>n;
vector<int> arr(n);
for(int i = 0; i < n; i++)
cin>>arr[i];
cout<<insertionSort(arr)<<endl;
}
}

Author: Song Hayoung
Link: https://songhayoung.github.io/2022/04/01/PS/HackerRank/insertion-sort/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.