归并排序
算法说明与实现代码:
归并排序(Merge Sort): 归并排序是一种分治算法,它将列表分成两个子列表,分别进行排序,然后将排序好的子列表合并成一个有序列表。
package main
import "fmt"
func merge(left, right []int) []int {
result := make([]int, 0, len(left)+len(right))
l, r := 0, 0
for l < len(left) && r < len(right) {
if left[l] < right[r] {
result = append(result, left[l])
l++
} else {
result = append(result, right[r])
r++
}
}
result = append(result, left[l:]...)
result = append(result, right[r:]...)
return result
}
func mergeSort(arr []int) []int {
if len(arr) <= 1 {
return arr
}
mid := len(arr) / 2
left := mergeSort(arr[:mid])
right := mergeSort(arr[mid:])
return merge(left, right)
}
func main() {
arr := []int{64, 34, 25, 12, 22, 11, 90}
fmt.Println("Unsorted array:", arr)
arr = mergeSort(arr)
fmt.Println("Sorted array:", arr)
}