排序算法
- 归并排序
采用递归思想,将数组分割成小的数组,分别排序,然后再将排序后的小数组合并,完成整个数组的排序。
以下是我用golang的实现,仅供参考。
package main
import "fmt"
func main() {
var lists = [][]int{
[]int{2, 4, 1, 7, 5, 9},
[]int{9, 6, 8, 2, 1, 6, 2, 0, 111},
[]int{1},
[]int{2, 4},
nil,
}
for _, list := range lists {
l4 := mergeSort(list)
fmt.Println(l4)
}
}
// mergeSort 归并排序
func mergeSort(l []int) []int {
length := len(l)
if length < 2 {
return l
}
middle := length / 2
left := l[:middle]
right := l[middle:]
return merge(mergeSort(left), mergeSort(right))
}
func merge(l, r []int) []int {
var result = make([]int, 0)
ll := len(l)
rl := len(r)
var i, j int
for i < ll || j < rl {
if j == rl {
result = append(result, l[i])
i++
} else if i == ll {
result = append(result, r[j])
j++
} else if l[i] <= r[j] {
result = append(result, l[i])
i++
} else if l[i] > r[j] {
result = append(result, r[j])
j++
}
}
return result
}
执行输出如下
[1 2 4 5 7 9]
[0 1 2 2 6 6 8 9 111]
[1]
[2 4]
[]