快速排序
func quickSort(arr []int) (res []int) {
if len(arr) < 2 {
return arr
}
leftArr := make([]int, 0)
rightArr := make([]int, 0)
middleVal := arr[0]
for k, v := range arr {
if k == 0 {
continue
}
if v < middleVal {
leftArr = append(leftArr, v)
} else {
rightArr = append(rightArr, v)
}
}
// if len(leftArr) > 0 {
leftArr = quickSort(leftArr)
// }
// if len(rightArr) > 0 {
rightArr = quickSort(rightArr)
// }
res = append(res, leftArr...)
res = append(res, middleVal)
res = append(res, rightArr...)
return
}
归并排序
func mergeSort(arr []int) []int {
if len(arr) < 2 {
return arr
}
mid := len(arr) / 2
leftArr := arr[:mid]
rightArr := arr[mid:]
leftArr = mergeSort(leftArr)
rightArr = mergeSort(rightArr)
out := mergeArr(leftArr, rightArr)
return out
}
func mergeArr(arr1, arr2 []int) []int {
var res = make([]int, len(arr1)+len(arr2), len(arr1)+len(arr2))
arrLen := len(arr1) + len(arr2)
i, j := 0, 0
for k := 0; k < arrLen; k++ {
if arr1[i] < arr2[j] {
res[k] = arr1[i]
i++
if i >= len(arr1) {
res = append(res[:k+1], arr2[j:]...)
break
}
} else {
res[k] = arr2[j]
j++
if j >= len(arr2) {
res = append(res[:k+1], arr1[i:]...)
break
}
}
}
return res
}