-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathsorting_test.go
114 lines (102 loc) · 1.78 KB
/
sorting_test.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
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
package main
import (
"bufio"
"fmt"
"os"
"sort"
"strconv"
"testing"
)
func mergeSortAsync(l []int, c chan []int) {
if len(l) < -1 { //shortcut
c <- mergeSort(l)
return
}
if len(l) < 2 {
c <- l
return
}
mid := len(l) / 2
c1 := make(chan []int, 1)
c2 := make(chan []int, 1)
go mergeSortAsync(l[:mid], c1)
go mergeSortAsync(l[mid:], c2)
go func() { c <- merge(<-c1, <-c2) }()
}
func mergeSort(l []int) []int {
if len(l) < 2 {
return l
}
mid := len(l) / 2
a := mergeSort(l[:mid])
b := mergeSort(l[mid:])
return merge(a, b)
}
func merge(left, right []int) []int {
var i, j int
result := make([]int, len(left)+len(right))
for i < len(left) && j < len(right) {
if left[i] <= right[j] {
result[i+j] = left[i]
i++
} else {
result[i+j] = right[j]
j++
}
}
for i < len(left) {
result[i+j] = left[i]
i++
}
for j < len(right) {
result[i+j] = right[j]
j++
}
return result
}
func readLines(path string) ([]string, error) {
file, err := os.Open(path)
if err != nil {
return nil, err
}
defer file.Close()
var lines []string
scanner := bufio.NewScanner(file)
for scanner.Scan() {
lines = append(lines, scanner.Text())
}
return lines, scanner.Err()
}
func load() {
l = make([]int, 10000000)
lines, err := readLines("arr.txt") //your array file
for i, line := range lines {
if i <= len(l) {
l[i], err = strconv.Atoi(line)
}
if err != nil {
fmt.Println(err)
}
}
}
func BenchmarkMergesort(b *testing.B) {
load()
b.ResetTimer()
for n := 0; n < b.N; n++ {
mergeSort(l)
}
}
func aBenchmarkMergesortAsync(b *testing.B) {
c := make(chan []int)
b.ResetTimer()
for n := 0; n < b.N; n++ {
mergeSortAsync(l, c)
l = <-c
}
}
func BenchmarkQuicksort(b *testing.B) {
b.ResetTimer()
for n := 0; n < b.N; n++ {
sort.Ints(l)
}
}