-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathinversions-mergesort.js
63 lines (53 loc) · 1.32 KB
/
inversions-mergesort.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
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
process.stdin.resume()
process.stdin.setEncoding('ascii')
let input_stdin = ''
let input_stdin_array = ''
let input_currentline = 0
process.stdin.on('data', function (data) {
input_stdin += data
})
process.stdin.on('end', function () {
input_stdin_array = input_stdin.split('\n')
main()
})
function readLine () {
return input_stdin_array[input_currentline++]
}
/// //////////// ignore above this line ////////////////////
let count
function countInversions (array) {
count = 0
array = mergeSort(array)
return count
}
function mergeSort (array) {
if (array.length < 2) {
return array
}
const middle = Math.floor(array.length / 2)
const left = array.slice(0, middle)
const right = array.slice(middle)
return merge(mergeSort(left), mergeSort(right))
}
function merge (left, right) {
const array = []
while (left.length && right.length) {
if (left[0] <= right[0]) {
array.push(left.shift())
} else {
count += left.length
array.push(right.shift())
}
}
return array.concat(left.slice()).concat(right.slice())
}
function main () {
let t = parseInt(readLine())
for (let a0 = 0; a0 < t; a0++) {
let n = parseInt(readLine())
let arr = readLine().split(' ')
arr = arr.map(Number)
let result = countInversions(arr)
process.stdout.write('' + result + '\n')
}
}