From e9b51b016096c7c89cc6dc15678acbc7bcbfb645 Mon Sep 17 00:00:00 2001 From: Kevin Cotugno Date: Wed, 14 Oct 2020 20:34:08 -0700 Subject: [PATCH] Add go merge sort --- go/merge_sort.go | 73 ++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 73 insertions(+) create mode 100644 go/merge_sort.go diff --git a/go/merge_sort.go b/go/merge_sort.go new file mode 100644 index 0000000..eba2fda --- /dev/null +++ b/go/merge_sort.go @@ -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)) +}