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 49 50 51 52 53 54 55 56 57 58 59 60
| func MergeSort2(arr []int) { temp := make([]int, len(arr)) copy(temp, arr) sort2(arr, 0, len(arr)-1, temp) }
func sort2(arr []int, l, r int, temp []int) { if r-l < 15 { insertionSort(arr, l, r) return } mid := l + (r-l)/2 sort2(arr, l, mid, temp) sort2(arr, mid+1, r, temp)
if arr[mid] > arr[mid+1] { merge2(arr, l, mid, r, temp) } }
func merge2(arr []int, l, mid, r int, temp []int) { copy(temp[l:r+1], arr[l:r+1]) i := l j := mid + 1
for k := l; k <= r; k++ { if i > mid { arr[k] = temp[j] j++ continue } else if j > r { arr[k] = temp[i] i++ continue } if temp[i] <= temp[j] { arr[k] = temp[i] i++ } else { arr[k] = temp[j] j++ } } }
func insertionSort(arr []int, l, r int) { for i := l; i <= r; i++ { var j int num := arr[i] for j = i; j-1 >= l && arr[j-1] > num; j-- { arr[j] = arr[j-1] } arr[j] = num } }
|