package main
import (
"fmt"
)
//归并排序
func MergeSort(arr []int) []int{
length := len(arr)
if length <= 1{
return arr
}
midindex := length/2
leftarr := MergeSort(arr[:midindex])
rightarr := MergeSort(arr[midindex:])
return Merge(leftarr,rightarr)
}
func Merge(leftarr,rightarr []int) []int{
leftindex,rightindex := 0,0
lastarr := []int{}
for leftindex < len(leftarr) && rightindex < len(rightarr){
if leftarr[leftindex] < rightarr[rightindex]{
lastarr=append(lastarr,leftarr[leftindex])
leftindex++
} else if leftarr[leftindex] > rightarr[rightindex]{
lastarr=append(lastarr,rightarr[rightindex])
rightindex++
} else {
lastarr=append(lastarr,leftarr[leftindex])
leftindex++
lastarr=append(lastarr,rightarr[rightindex])
rightindex++
}
}
for leftindex < len(leftarr){
lastarr=append(lastarr,leftarr[leftindex])
leftindex++
}
for rightindex < len(leftarr){
lastarr=append(lastarr,rightarr[rightindex])
rightindex++
}
return lastarr
}
func main(){
arr := []int{11,1,19,232,29, 30, 2, 5, 45, 8, 234, 12, 63}
//fmt.Println(BubblesortMax(arr))
fmt.Println(MergeSort(arr))
}
网友评论