AcWing 787. 归并排序-go
原题链接
简单
作者:
没头脑不高兴
,
2020-09-03 11:06:32
,
所有人可见
,
阅读 405
package main
import "fmt"
/*
两个有序序列合并为一个有序序列
*/
func merge_sort(l []int, low, high int) {
if low >= high {
return
}
mid := (low + high) >> 1
//fmt.Println(mid)
merge_sort(l, low, mid)
merge_sort(l, mid+1, high)
k := 0
i, j := low, mid+1
tmp := make([]int, len(l))
// 比较大小输入到临时序列
for i <= mid && j <= high {
if l[i] <= l[j] {
tmp[k] = l[i]
i++
k++
} else {
tmp[k] = l[j]
k++
j++
}
}
//剩左半边
for i <= mid {
tmp[k] = l[i]
k++
i++
}
// 剩右半边
for j <= high {
tmp[k] = l[j]
k++
j++
}
// 临时序列输出到原序列
for i, j := low, 0; i <= high; i++ {
l[i] = tmp[j]
j++
}
}
func main() {
var m int
fmt.Scanf("%d\n", &m)
ll := make([]int, m)
for i := 0; i < m; i++ {
fmt.Scanf("%d", &ll[i])
}
//ll := []int{2, 3, 1, 5, 4}
merge_sort(ll, 0, len(ll)-1)
fmt.Println(ll)
}