Merge sort
A simple implementation of merge sort algorithm in Go
package main
import (
"fmt"
"math"
"sync"
)
func merger(list []int, p uint, q uint, r uint) {
var L []int
var R []int
L = append(L, list[p:q+1]...)
L = append(L, math.MaxInt)
R = append(R, list[q+1:r+1]...)
R = append(R, math.MaxInt)
i := 0
j := 0
for k := p; k <= r; k++ {
if L[i] < R[j] {
list[k] = L[i]
i++
} else {
list[k] = R[j]
j++
}
}
}
func merge(list []int, p uint, r uint) {
var wg sync.WaitGroup
wg.Add(2)
if p < r {
q := (p + r) / 2
go func() {
merge(list, p, q)
wg.Done()
}()
go func() {
merge(list, q+1, r)
wg.Done()
}()
wg.Wait()
merger(list, p, q, r)
}
}
func mergeSort(list []int) {
merge(list, 0, uint(len(list)-1))
}
func main() {
a := []int{2, 1, 3, 5, -4, -4, 6, -8, 7, 0}
// O(nlogn)
mergeSort(a)
fmt.Println(a)
}