-
Notifications
You must be signed in to change notification settings - Fork 0
/
inversionCount_1.go
59 lines (50 loc) · 1.07 KB
/
inversionCount_1.go
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
package main
import (
"fmt"
"io/ioutil"
"strconv"
"sort"
"strings"
)
func countSplitInversion(firstHalf []int, secondHalf []int) int {
inversionCount := 0
sort.Ints(firstHalf)
sort.Ints(secondHalf)
for len(firstHalf) > 0 && len(secondHalf) > 0 {
if firstHalf[0] <= secondHalf[0] {
firstHalf = firstHalf[1:]
} else {
secondHalf = secondHalf[1:]
inversionCount += len(firstHalf)
}
}
return inversionCount
}
func inversionCount(arr []int) int {
arrCount := len(arr)
if arrCount <= 1 {
return 0
}
firstHalf := arr[:arrCount/2]
secondHalf := arr[arrCount/2:]
x := inversionCount(firstHalf)
y := inversionCount(secondHalf)
z := countSplitInversion(firstHalf, secondHalf)
return x + y + z
}
func main() {
fileContent, err := ioutil.ReadFile("IntegerArray.txt")
if err != nil {
panic(err)
}
stringArray := strings.Fields(string(fileContent))
intArray := []int{}
for _, v := range stringArray {
intVal, err := strconv.Atoi(v)
if err != nil {
panic(err)
}
intArray = append(intArray, intVal)
}
fmt.Println(inversionCount(intArray))
}