-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathcountInversions.js
31 lines (30 loc) · 916 Bytes
/
countInversions.js
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
//+ Jonas Raoni Soares Silva
//@ http://raoni.org
// An in-place iterative merge sort algorithm, that simply counts the required switches
function countInversions(arr) {
let
inversions = 0,
l = arr.length,
buffer = new Array(l);
for (let size = 1; size < l; size <<= 1) {
for (let leftStart = 0; leftStart < l; leftStart += 2 * size) {
let
left = leftStart,
right = Math.min(left + size, l),
leftLimit = right,
rightLimit = Math.min(right + size, l),
i = left;
while (left < leftLimit && right < rightLimit) {
const useLeft = arr[left] <= arr[right];
// Here we count the switches :D
if (!useLeft)
inversions += leftLimit - left;
buffer[i++] = arr[useLeft ? left++ : right++];
}
for (; left < leftLimit; buffer[i++] = arr[left++]);
for (; right < rightLimit; buffer[i++] = arr[right++]);
}
[arr, buffer] = [buffer, arr];
}
return inversions;
}