Skip to content

Instantly share code, notes, and snippets.

@zignd
Created January 23, 2022 20:21
Show Gist options
  • Select an option

  • Save zignd/c0f23824ecf6706431d83224d70f5421 to your computer and use it in GitHub Desktop.

Select an option

Save zignd/c0f23824ecf6706431d83224d70f5421 to your computer and use it in GitHub Desktop.
Merge Sort in Go using Generics
package main
import (
"constraints"
"fmt"
)
func main() {
input := []int{9, 5, 7, 3, 4, 1, 0, 2}
fmt.Printf(" input: %v\n", input)
result := mergeSort(input)
fmt.Printf("result: %v\n", result)
input2 := []string{"bbb", "aaa", "ddd", "ccc", "ggg", "fff"}
fmt.Printf(" input: %v\n", input2)
result2 := mergeSort(input2)
fmt.Printf("result: %v\n", result2)
}
func mergeSort[T constraints.Ordered](arr []T) []T {
if len(arr) <= 1 {
return arr
}
mid := len(arr) / 2
left := make([]T, len(arr[:mid]))
copy(left, arr[:mid])
right := make([]T, len(arr[mid:]))
copy(right, arr[mid:])
mergeSort(left)
mergeSort(right)
var i, j, k int
for i < len(left) && j < len(right) {
if left[i] < right[j] {
arr[k] = left[i]
i += 1
} else {
arr[k] = right[j]
j += 1
}
k += 1
}
for i < len(left) {
arr[k] = left[i]
i += 1
k += 1
}
for j < len(right) {
arr[k] = right[j]
j += 1
k += 1
}
return arr
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment