1、归并排序
package main
import (
"fmt"
"math/rand"
)
func main() {
var z []int
for i := 0; i < 10; i++ {
z = append(z, rand.Intn(10))
}
mergeSort(z, 0, 9)
}
func mergeSort(nums []int, start, end int) {
if start >= end {
return
}
mid := (start + end) / 2
mergeSort(nums, start, mid)
mergeSort(nums, mid+1, end)
merge(nums, start, mid, end)
}
func merge(nums []int, start, mid, end int) {
temp := []int{}
s1, s2 := start, mid+1
for s1 <= mid && s2 <= end {
if nums[s1] > nums[s2] {
temp = append(temp, nums[s2]) //小的append在前面
s2++
} else {
temp = append(temp, nums[s1])
s1++
}
}
if s1 <= mid { //前面一个子数组未比较的数直接append
temp = append(temp, nums[s1:mid+1]...)
}
if s2 <= end { //后面一个子数组未比较的数直接append
temp = append(temp, nums[s2:end+1]...)
}
for pos, item := range temp {
nums[start+pos] = item
}
}