归并排序
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 | // 归并排序 // 主要是merge func MergeSort(arr []int) {<!-- --> arrLen := len(arr) if arrLen <= 1 {<!-- --> return } mergeSort(arr, 0, arrLen-1) } func mergeSort(arr []int, start, end int) {<!-- --> if start >= end {<!-- --> return } mid := (start + end) / 2 mergeSort(arr, start, mid) mergeSort(arr, mid+1, end) merge(arr, start, mid, end) } func merge(arr []int, start, mid, end int) {<!-- --> tmpArr := make([]int, end-start+1) i := start j := mid + 1 k := 0 for ; i <= mid && j <= end; k++ {<!-- --> if arr[i] < arr[j] {<!-- --> tmpArr[k] = arr[i] i++ } else {<!-- --> tmpArr[k] = arr[j] j++ } } for ; i <= mid; i++ {<!-- --> tmpArr[k] = arr[i] k++ } for ; j <= end; j++ {<!-- --> tmpArr[k] = arr[j] k++ } copy(arr[start:end+1], tmpArr) } |
快排
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 | // 快排 func QuickSort(arr []int) {<!-- --> separateSort(arr, 0, len(arr)-1) } func separateSort(arr []int, start, end int) {<!-- --> if start >= end {<!-- --> return } i := partition(arr, start, end) separateSort(arr, start, i-1) separateSort(arr, i+1, end) } func partition(arr []int, start, end int) int {<!-- --> // 选取最后一位当对比数字 pivot := arr[end] var i = start for j := start; j < end; j++ {<!-- --> if arr[j] < pivot {<!-- --> if !(i == j) {<!-- --> // 交换位置 arr[i], arr[j] = arr[j], arr[i] } i++ } } arr[i], arr[end] = arr[end], arr[i] return i } |