package mergeSort
func mergeSort(nums []int) []int {
if len(nums) < 2 {
return nums
}
m := len(nums) / 2
l := mergeSort(nums[:m])
r := mergeSort(nums[m:])
return merge(l, r)
}
func merge(left, right []int) []int {
i, j := 0, 0
n, m := len(left), len(right)
reslet := make([]int, n+m)
for i < n && j < m {
if left[i] <= right[j] {
reslet[i+j] = left[i]
i++
} else {
reslet[i+j] = right[j]
j++
}
}
for i < n {
reslet[i+j] = left[i]
i++
}
for j < m {
reslet[i+j] = right[j]
j++
}
return reslet
}
package mergeSort
import (
"math/rand"
"testing"
"time"
)
func TestMergeSort(t *testing.T) {
var input [100]int
r := rand.New(rand.NewSource(time.Now().Unix()))
// 初始化数组input[]
for i := 0; i < 100; i++ {
input[i] = r.Intn(1000)
}
output := mergeSort(input[:])
for i := 0; i <= 10; i++ {
println(output[i])
}
}
相关文章
暂无评论...