-
Notifications
You must be signed in to change notification settings - Fork 0
/
5_merge_sort.go
42 lines (40 loc) · 1.16 KB
/
5_merge_sort.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
package algorithm
// MergeSort ..
// No.5
// 归并排序(稳定)算法步骤:
// 1. 申请空间,使其大小为两个已经排序序列之和,该空间用来存放合并后的序列;
// 2. 设定两个指针,最初位置分别为两个已经排序序列的起始位置;
// 3. 比较两个指针所指向的元素,选择相对小的元素放入到合并空间,并移到指针到下一位置;
// 4. 重复步骤3直到某一指针达到序列尾;
// 5. 将另一序列剩下的所有元素直接复制到合并序列尾。
func mergeSort(arr []int) []int {
length := len(arr)
if length < 2 {
return arr
}
middle := length / 2
left := arr[0:middle]
right := arr[middle:]
return merge(mergeSort(left), mergeSort(right))
}
func merge(left []int, right []int) []int {
var result []int
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:]
}
}
for len(left) != 0 {
result = append(result, left[0])
left = left[1:]
}
for len(right) != 0 {
result = append(result, right[0])
right = right[1:]
}
return result
}