github.com/benz9527/toy-box/algo@v0.0.0-20240221120937-66c0c6bd5abd/sort/merge.go (about) 1 package sort 2 3 /* 4 https://www.programiz.com/dsa/merge-sort 5 Based on the principle of Divide and Conquer Algorithm 6 */ 7 8 func divideAndConquer(arr []int, leftIdx int, rightIdx int) { 9 if leftIdx >= rightIdx { 10 return 11 } 12 13 middleIdx := (leftIdx + rightIdx) / 2 14 15 divideAndConquer(arr, leftIdx, middleIdx) 16 divideAndConquer(arr, middleIdx+1, rightIdx) 17 18 merge(arr, leftIdx, middleIdx, rightIdx) 19 } 20 21 func merge(arr []int, subl int, subm int, subr int) { 22 n1 := subm - subl + 1 23 n2 := subr - subm 24 25 arrL := []int{} 26 arrR := []int{} 27 28 for i := 0; i < n1; i++ { 29 arrL = append(arrL, arr[subl+i]) 30 } 31 32 for i := 0; i < n2; i++ { 33 arrR = append(arrR, arr[subm+1+i]) 34 } 35 36 i, j, k := 0, 0, subl 37 38 for i < n1 && j < n2 { 39 if arrL[i] <= arrR[j] { 40 arr[k] = arrL[i] 41 i++ 42 } else { 43 arr[k] = arrR[j] 44 j++ 45 } 46 k++ 47 } 48 49 for i < n1 { 50 arr[k] = arrL[i] 51 i++ 52 k++ 53 } 54 55 for j < n2 { 56 arr[k] = arrR[j] 57 j++ 58 k++ 59 } 60 } 61 62 func MergeSort(arr []int) { 63 n := len(arr) 64 divideAndConquer(arr, 0, n-1) 65 }