本方法通过二分法来实现有序序列下插入新的元素,通过测试,本方法比标准库方法快了接近10倍。
main.go
package main
import "fmt"
func BinarySort(arr []int, num int) []int {
if len(arr) == 0 {
arr = append(arr, num)
return arr
}
left := 0
right := len(arr) - 1
if num >= (arr)[right] {
arr = append(arr, num)
return arr
} else if num <= (arr)[left] {
arr = append([]int{num}, arr...)
return arr
}
var mid int
for left <= right {
mid = (left + right) >> 1
if arr[mid] <= num && mid+1 <= len(arr)-1 && arr[mid+1] >= num {
arr = append(arr, 0)
copy(arr[mid+2:], arr[mid+1:])
arr[mid+1] = num
return arr
} else if arr[mid] <= num {
left = mid
} else if arr[mid] > num {
right = mid
}
}
return arr
}
func main() {
arr := []int{100, 4, 5, 6, 3, 4, 2, 4, 10, 32, 4, 5, 6, 7, 5, 7, 5, 4, 3, 4, 344, 34, 5, 65, 45, 34, 34, 342, 34, 67, 45, 76, 879, 9, 4, 3, 67, 4,
5, 6, 3, 2, 45, 3, 34, 43, 2, 54, 34, 6, 7, 4, 7, 3, 7, 3, 6, 34, 3, 23, 23, 5, 34, 64, 324, 2345, 456, 2, 1}
var m []int
for i := range arr {
m = BinarySort(m, arr[i])
}
fmt.Println(m)
}
基准测试函数,main_test.go
package main
import (
"github.com/stretchr/testify/assert"
"math/rand"
"sort"
"testing"
"time"
)
func BenchmarkFib(b *testing.B) {
for n := 0; n < b.N; n++ {
arr := []int{100, 4, 5, 6, 3, 4, 2, 4, 10, 32, 4, 5, 6, 7, 5, 7, 5, 4, 3, 4, 344, 34, 5, 65, 45, 34, 34, 342, 34, 67, 45, 76, 879, 9, 4, 3, 67, 4,
5, 6, 3, 2, 45, 3, 34, 43, 2, 54, 34, 6, 7, 4, 7, 3, 7, 3, 6, 34, 3, 23, 23, 5, 34, 64, 324, 2345, 456, 2, 1}
m := make([]int, len(arr))
for i := range arr {
m = append(m, arr[i])
sort.Ints(m)
}
}
}
func BenchmarkFia(b *testing.B) {
for n := 0; n < b.N; n++ {
arr := []int{100, 4, 5, 6, 3, 4, 2, 4, 10, 32, 4, 5, 6, 7, 5, 7, 5, 4, 3, 4, 344, 34, 5, 65, 45, 34, 34, 342, 34, 67, 45, 76, 879, 9, 4, 3, 67, 4,
5, 6, 3, 2, 45, 3, 34, 43, 2, 54, 34, 6, 7, 4, 7, 3, 7, 3, 6, 34, 3, 23, 23, 5, 34, 64, 324, 2345, 456, 2, 1}
m := make([]int, len(arr))
for i := range arr {
m = BinarySort(m, arr[i])
}
}
}
func TestFib(t *testing.T) {
adder := func(x, y int) bool {
return x <= y
}
rand.Seed(time.Now().Unix())
for i := 0; i < 10000; i++ {
arr := make([]int, 0)
for j := 0; j < 100; j++ {
arr = append(arr, rand.Intn(100000))
}
m := make([]int, len(arr))
for i := range arr {
m = BinarySort(m, arr[i])
}
for k := 0; k < len(m)-1; k++ {
assert.Equal(t, true, adder(m[k], m[k+1]))
}
}
}