<script>
function getSum(BITree, index)
{
let sum = 0;
while (index > 0)
{
sum += BITree[index];
index -= index & (-index);
}
return sum;
}
function updateBIT(BITree, n, index, val)
{
while (index <= n)
{
BITree[index] += val;
index += index & (-index);
}
}
function convert(arr, n)
{
let temp = new Array(n);
for (let i = 0; i < n; i++)
temp[i] = arr[i];
temp.sort(function(a, b){return a - b});
for (let i = 0; i < n; i++)
{
arr[i] = lower_bound(temp, 0, n, arr[i]) + 1;
}
}
function lower_bound(a, low, high, element)
{
while(low < high)
{
let middle = low + parseInt((high - low) / 2, 10);
if(element > a[middle])
low = middle + 1;
else
high = middle;
}
return low;
}
function getInvCount(arr, k, n)
{
let invcount = 0;
convert(arr, n);
let BIT = new Array(n + 1);
for (let i = 1; i <= n; i++)
BIT[i] = 0;
for (let i = k - 1; i >= 0; i--)
{
invcount += getSum(BIT, arr[i] - 1);
updateBIT(BIT, n, arr[i], 1);
}
let ans = invcount;
let x = 0, j = k, icnt = 0, jcnt = 0;
while (j <= n - 1)
{
icnt = getSum(BIT, arr[x] - 1);
updateBIT(BIT, n, arr[x], -1);
jcnt = getSum(BIT, n) - getSum(BIT, arr[j]);
updateBIT(BIT, n, arr[j], 1);
invcount = invcount - icnt + jcnt;
ans = ans + invcount;
x++; j++;
}
return ans;
}
let arr = [ 7, 3, 2, 4, 1 ];
let k = 3;
let n = arr.length;
document.write("Number of inversions in all " +
"subarrays of size " + k +
" are : " + getInvCount(arr, k, n));
</script>