Created
June 28, 2019 14:23
-
-
Save scue/f35ad5913b5bf95215f4486b8848be82 to your computer and use it in GitHub Desktop.
Go语言归并排序算法
This file contains 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 "log" | |
func MergeSort(a []int) []int { | |
l := len(a) | |
if l <= 1 { | |
return a | |
} | |
// split | |
left := MergeSort(a[:l/2]) | |
right := MergeSort(a[l/2:]) | |
// merge | |
result := make([]int, l) | |
var lIndex, rIndex int | |
for i := 0; i < l; i++ { | |
switch { | |
case rIndex >= len(right): // right is empty | |
result[i] = left[lIndex] | |
lIndex++ | |
case lIndex >= len(left): // left is empty | |
result[i] = right[rIndex] | |
rIndex++ | |
case left[lIndex] < right[rIndex]: // head element left < right | |
result[i] = left[lIndex] | |
lIndex++ | |
default: // else | |
result[i] = right[rIndex] | |
rIndex++ | |
} | |
} | |
return result | |
} | |
func main() { | |
log.Println(MergeSort([]int{})) | |
log.Println(MergeSort([]int{6})) | |
log.Println(MergeSort([]int{1, 2})) | |
log.Println(MergeSort([]int{5, 2})) | |
log.Println(MergeSort([]int{6, 4, 3, 2, 1, 5})) | |
log.Println(MergeSort([]int{5, 2, 0, 1, 3, 1, 4})) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
输出信息: