-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy patharray-inversion-count.js
43 lines (37 loc) · 1.42 KB
/
array-inversion-count.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
32
33
34
35
36
37
38
39
40
41
42
43
function merge (left, right) {
let resultArray = [], leftIndex = 0, rightIndex = 0, counter = 0;
let existing_c = left[1] + right[1];
left = left[0];
right = right[0];
// We will concatenate values into the resultArray in order
while (leftIndex < left.length && rightIndex < right.length) {
if (left[leftIndex] <= right[rightIndex]) {
resultArray.push(left[leftIndex]);
leftIndex++; // move left array cursor
} else {
resultArray.push(right[rightIndex]);
rightIndex++; // move right array cursor
counter += (left.length - leftIndex)
}
}
// We need to concat here because there will be one element remaining
// from either left OR the right
return [resultArray.concat(left.slice(leftIndex)).concat(right.slice(rightIndex)),
existing_c + counter]
}
function mergeSort (unsortedArray) {
// No need to sort the array if the array only has one element or empty
if (unsortedArray.length <= 1) {
return [unsortedArray, 0];
}
// In order to divide the array in half, we need to figure out the middle
const middle = Math.floor(unsortedArray.length / 2);
// This is where we will be dividing the array into left and right
const left = unsortedArray.slice(0, middle);
const right = unsortedArray.slice(middle);
// Using recursion to combine the left and right
return merge(
mergeSort(left), mergeSort(right)
);
}
console.log(mergeSort([1, 1, 1, 2, 2]));