-
Notifications
You must be signed in to change notification settings - Fork 8
/
Copy pathmain.go
61 lines (50 loc) · 1.05 KB
/
main.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
package main
import (
"fmt"
"math/rand"
"time"
)
func merge(left, right []int) []int {
result := make([]int, 0, len(left) + len(right))
for len(left) > 0 && len(right) > 0 {
if left[0] < right[0] {
result = append(result, left[0])
left = left[1:]
} else {
result = append(result, right[0])
right = right[1:]
}
}
if len(left) > 0 {
result = append(result, left...)
}
if len(right) > 0 {
result = append(result, right...)
}
return result
}
func mergeSort(arr []int) []int {
if len(arr) < 2 {
return arr
}
mid := len(arr) / 2
left, right := arr[:mid], arr[mid:]
return merge(mergeSort(left), mergeSort(right))
}
func main() {
total := 20
left := 1
right := 1000
arr := generateRandomArray(total, left, right)
fmt.Println("Origin array: ", arr)
arr = mergeSort(arr)
fmt.Println("Sorted array: ", arr)
}
func generateRandomArray(total, left, right int) []int {
arr := make([]int, total)
rand.Seed(time.Now().UnixNano())
for i := 0; i < total; i++ {
arr[i] = rand.Intn(right - left) + left
}
return arr
}