Skip to content

Instantly share code, notes, and snippets.

@srph
Last active December 27, 2019 01:29
Show Gist options
  • Save srph/d9457add84b3c56ee02fee1565ffe294 to your computer and use it in GitHub Desktop.
Save srph/d9457add84b3c56ee02fee1565ffe294 to your computer and use it in GitHub Desktop.
Go: Merge sort - programming exercise
package main
import (
"fmt"
)
func main() {
list := []int{38, 27, 24, 56, -16, 12, 32, -3, 16, 11, 15, 25, 29}
fmt.Printf("Original: %v\n", mergeSort(list))
fmt.Printf("Post-Merge Sort: %v\n", merged)
}
func mergeSort(list []int) []int {
if len(list) <= 1 {
return list
}
middle := len(list) / 2
left := list[:middle]
right := list[middle:]
return merge(mergeSort(left), mergeSort(right))
}
func merge(left []int, right []int) []int {
var result []int
lindex := 0
rindex := 0
for lindex < len(left) && rindex < len(right) {
if left[lindex] < right[rindex] {
result = append(result, left[lindex])
lindex++
} else {
result = append(result, right[rindex])
rindex++
}
}
return append(append(result, left[lindex:]...), right[rindex:]...)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment