-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathproblem044.go
More file actions
35 lines (33 loc) · 1.18 KB
/
Copy pathproblem044.go
File metadata and controls
35 lines (33 loc) · 1.18 KB
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
package problem044
func mergeSort(values []int) (sortedValues []int, inversionCount int) {
if len(values) <= 1 {
sortedValues, inversionCount = values, 0
return
}
mid := len(values) / 2
sortedLefties, leftInversionCount := mergeSort(values[:mid])
sortedRighties, rightInversionCount := mergeSort(values[mid:])
inversionCount += leftInversionCount + rightInversionCount
for leftIndex, rightIndex := 0, 0; leftIndex < len(sortedLefties) || rightIndex < len(sortedRighties); {
switch {
case rightIndex >= len(sortedRighties):
sortedValues = append(sortedValues, sortedLefties[leftIndex])
leftIndex++
case leftIndex >= len(sortedLefties):
sortedValues = append(sortedValues, sortedRighties[rightIndex])
rightIndex++
case sortedLefties[leftIndex] <= sortedRighties[rightIndex]:
sortedValues = append(sortedValues, sortedLefties[leftIndex])
leftIndex++
case sortedLefties[leftIndex] > sortedRighties[rightIndex]:
sortedValues = append(sortedValues, sortedRighties[rightIndex])
inversionCount += len(sortedLefties) - leftIndex
rightIndex++
}
}
return
}
func CountInversions(values []int) (inversionCount int) {
_, inversionCount = mergeSort(values)
return
}