三路归并 go语言实现
func merge(leftarr, midarr, rightarr []int) []int {
leftIndex := 0
midIndex := 0
rightIndex := 0
lastarr := make([]int, 0)
for leftIndex < len(leftarr) && midIndex < len(midarr) && rightIndex < len(rightarr) {
if leftarr[leftIndex] > rightarr[rightIndex] && midarr[midIndex] > rightarr[rightIndex] {
lastarr = append(lastarr, rightarr[rightIndex])
rightIndex++
} else if leftarr[leftIndex] < rightarr[rightIndex] && leftarr[leftIndex] < midarr[midIndex] {
lastarr = append(lastarr, leftarr[leftIndex])
leftIndex++
} else if midarr[midIndex] < leftarr[leftIndex] && midarr[midIndex] < rightarr[rightIndex] {
lastarr = append(lastarr, midarr[midIndex])
midIndex++
} else {
lastarr = append(lastarr, rightarr[rightIndex])
lastarr = append(lastarr, midarr[midIndex])
lastarr = append(lastarr, leftarr[leftIndex])
rightIndex++
midIndex++
leftIndex++
}
}
for leftIndex < len(leftarr) {
lastarr = append(lastarr, leftarr[leftIndex])
leftIndex++
}
for midIndex < len(midarr) {
lastarr = append((lastarr, midarr[midIndex]))
}
for rightIndex < len(rightarr) {
lastarr = append(lastarr, rightarr[rightIndex])
rightIndex++
}
return lastarr
}
func MergeScort(arr []int) []int {
length := len(arr)
if length <= 3 {
return arr
} else {
mid01 := length / 3
mid02 := mid01 * 2
leftarr := MergeScort(arr[:mid01])
middlearr := MergeScort(arr[mid01:mid02])
rightarr := MergeScort(arr[mid02:])
return merge(leftarr, middlearr, rightarr)
}
}