-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcountInversion.go
More file actions
132 lines (100 loc) · 1.76 KB
/
countInversion.go
File metadata and controls
132 lines (100 loc) · 1.76 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
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
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
package main
import (
"bufio"
"fmt"
"os"
"strconv"
)
func main() {
//txt file from the course assignment containing 10,00000 integers
f, err := os.Open("count_inversion.txt")
if err != nil {
panic(err)
}
defer f.Close()
scanner := bufio.NewScanner(f)
var datas []int
for scanner.Scan() {
d, _ := strconv.Atoi(scanner.Text())
datas = append(datas, d)
}
_, n := sort_and_split(datas)
fmt.Println(n)
//output correct answer 2407905288
}
func sort_and_split(data []int) ([]int, int) {
//base case
if len(data) == 0 || len(data) == 1 {
return data, 0
}
//divide
mid := len(data) / 2
left := data[:mid]
right := data[mid:]
//conqur
a, x := sort_and_split(left)
b, y := sort_and_split(right)
z := count_split_inversion(a, b)
//combine
return mergeSort(data), x + y + z
}
func count_split_inversion(a, b []int) int {
i := 0
j := 0
total := 0
n := len(a) + len(b)
for idx := 0; idx < n; idx++ {
if j == len(b) {
break
}
if i == len(a) {
break
}
if a[i] > b[j] {
total += len(a) - i
j++
} else {
i++
}
}
return total
}
//2-way-mergeSort
func mergeSort(arr []int) []int {
n := len(arr)
if n == 1 {
return arr
}
mid := n / 2
sortedLeft := mergeSort(arr[:mid])
sortedRight := mergeSort(arr[mid:])
return merge(sortedLeft, sortedRight)
}
func merge(left, right []int) []int {
i := 0
j := 0
n := len(left) + len(right)
out := make([]int, n)
for idx := 0; idx < n; idx++ {
if i == len(left) {
for k := 0; k < len(right)-j; k++ {
out[idx+k] = right[j+k]
}
break
}
if j == len(right) {
for k := 0; k < len(left)-i; k++ {
out[idx+k] = left[i+k]
}
break
}
if left[i] >= right[j] {
out[idx] = right[j]
j++
} else {
out[idx] = left[i]
i++
}
}
return out
}