Skip to content

Instantly share code, notes, and snippets.

@caryyu
Created September 30, 2021 05:21
Show Gist options
  • Save caryyu/cb71b850574e8ddf47c4b20ab1b0242c to your computer and use it in GitHub Desktop.
Save caryyu/cb71b850574e8ddf47c4b20ab1b0242c to your computer and use it in GitHub Desktop.
Algorithm of mergesort
package main
import "fmt"
func main() {
var nums []int = []int{10, 7, 8, 1, 4, 3}
topDownMergesort(nums)
fmt.Println(nums)
}
func topDownMergesort(a []int) {
var b []int = make([]int, len(a))
copy(b, a)
topDownSplitMerge(b, 0, len(b), a)
}
func topDownSplitMerge(b []int, idx1 int, idx2 int, a []int) {
if idx2-idx1 <= 1 {
return
}
var middle int = (idx2 + idx1) / 2
topDownSplitMerge(a, idx1, middle, b)
topDownSplitMerge(a, middle, idx2, b)
topDownMerge(b, idx1, middle, idx2, a)
}
func topDownMerge(a []int, idx1 int, middle int, idx2 int, b []int) {
i := idx1
j := middle
for k := idx1; k < idx2; k++ {
if i < middle && (j >= idx2 || a[i] <= b[j]) {
b[k] = a[i]
i++
} else {
b[k] = a[j]
j++
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment