Last active
December 27, 2019 01:29
-
-
Save srph/d9457add84b3c56ee02fee1565ffe294 to your computer and use it in GitHub Desktop.
Go: Merge sort - programming exercise
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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