Add go merge sort

This commit is contained in:
Kevin Cotugno 2020-10-14 20:34:08 -07:00
parent 2c564c9e82
commit e9b51b0160

73
go/merge_sort.go Normal file
View File

@ -0,0 +1,73 @@
package main
import (
"fmt"
)
var list = []int{1, 55, 3, 6, 4, 95, 23, 57, 2, 8, 5}
func Merge(a, b []int) []int {
result := make([]int, len(a)+len(b))
n1 := len(a)
n2 := len(b)
var i, j, k int
for i < n1 && j < n2 {
if a[i] < b[j] {
result[k] = a[i]
i++
} else {
result[k] = b[j]
j++
}
k++
}
for i < n1 {
result[k] = a[i]
k++
i++
}
for j < n2 {
result[k] = b[j]
k++
j++
}
return result
}
func Sort(unsorted []int) []int {
result := make([]int, len(unsorted))
if len(unsorted) == 1 {
result[0] = unsorted[0]
} else {
i := 0
j := 1
if unsorted[0] > unsorted[1] {
i, j = j, i
}
result[0], result[1] = unsorted[i], unsorted[j]
}
return result
}
func MergeSort(unsorted []int) []int {
if len(unsorted) <= 2 {
return Sort(unsorted)
}
half := len(unsorted) / 2
return Merge(MergeSort(unsorted[0:half]), MergeSort(unsorted[half:len(unsorted)]))
}
func main() {
fmt.Println(list)
fmt.Println(MergeSort(list))
}