-
Notifications
You must be signed in to change notification settings - Fork 0
/
mergesort.go
69 lines (57 loc) · 934 Bytes
/
mergesort.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
60
61
62
63
64
65
66
67
68
69
package main
import (
"fmt"
"math/rand"
)
func merge(a []int, b []int) []int {
var r = make([]int, len(a)+len(b))
var i = 0
var j = 0
for i < len(a) && j < len(b) {
if a[i] <= b[j] {
r[i+j] = a[i]
i++
} else {
r[i+j] = b[j]
j++
}
}
for i < len(a) {
r[i+j] = a[i]
i++
}
for j < len(b) {
r[i+j] = b[j]
j++
}
return r
}
func Mergesort(items []int) chan []int {
out := make(chan []int)
go func() {
if len(items) < 2 {
out <- items
return
}
var middle = len(items) / 2
left := Mergesort(items[:middle])
right := Mergesort(items[middle:])
a := <-left
b := <-right
out <- merge(a, b)
}()
return out
}
func randIntArray(length int) []int {
input := make([]int, length)
for i := 0; i < length; i += 1 {
input[i] = rand.Int()
}
return input
}
func main() {
input := randIntArray(10000)
result := Mergesort(input)
solution := <-result
fmt.Println(solution)
}