有序序列插入新的元素(基于二分法的插入排序法)

本方法通过二分法来实现有序序列下插入新的元素,通过测试,本方法比标准库方法快了接近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]))
		}
	}
}


测试结果
在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

不知所措。

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值