数据结构与算法 — 二分法/折半查找 (Golang)
1 二分法查找的前提
在一个单调性质的数组内,查找一个数字,要求找到这个元素的开始位置和结束位置。【单调递增或单调递减的数组】
2 实现代码
package main
import "fmt"
/*
*
二分法查找有序集合中指定元素的代码
*/
func main() {
array := []int{1, 2, 2, 2, 3, 4, 4, 5, 7, 9, 10}
target := 2
//index := BinarySearchElement(array, target)
index1 := BinarySearchElement1(array, target, true)
fmt.Println(target, "的位置为:", index1)
}
// BinarySearchElement 1、二分法查找有序集合中是否有指定元素,如果有则返回其索引,若无则返回-1
func BinarySearchElement(array []int, target int) int {
index := -1
left := 0
right := len(array) - 1
for left <= right { //注意此处可以为等号
mid := (left + right) / 2
if target == array[mid] {
index = mid
break
} else if target < array[mid] {
right = mid - 1
} else {
left = mid + 1
}
}
return index
}
// BinarySearchElement1 2、二分法查找有序集合中是否有指定元素,且其第一次或最后一次出现的位置,如果有则返回其索引,若无则返回-1,isLeft:true:第一次出现的位置;false:最后一次出现的位置
func BinarySearchElement1(array []int, target int, isLeft bool) int {
index := -1
left := 0
right := len(array) - 1
for left <= right { //注意此处需要加等号,否则当数组中的元素为奇数个时,查找左边界,最后会推算到 left =1,right=1,而此时2的左边界恰好在1处,如果没有等号,则1处的2就会被忽略
mid := (left + right) / 2
if target < array[mid] {
right = mid - 1
} else if target > array[mid] {
left = mid + 1
} else {
index = mid
if isLeft { //往左搜索
right = mid - 1
} else { //往右搜索
left = mid + 1
}
}
}
return index
}
3 细节
1、查找时注意数组的左右边界分别位置是 left = 0,right = len(array)-1。
2、for left <= right
,此处必须是小于等于。否则按照示例给出的数组,当有奇数
个元素,且待查找元素在1时,会被忽略,导致漏查1处的元素。
4 时间复杂度
参考:二分法时间复杂度
时间复杂度是logN。
5 单元测试
package main
import "testing"
// TestBinarySearchElement 手写
func TestBinarySearchElement(t *testing.T) {
array := []int{1, 2, 2, 2, 3, 4, 4, 5, 7, 9, 10}
target1 := 11
got1 := BinarySearchElement(array, target1)
want := 0
if got1 < want {
t.Errorf("got %d want %d", got1, want)
}
}
// TestBinarySearchElement1 自动生成
func TestBinarySearchElement1(t *testing.T) {
type args struct {
array []int
target int
isLeft bool
}
tests := []struct {
name string
args args
want int
}{
{
name: "第一次测试",
args: args{
array: []int{1, 2, 2, 2, 3, 4, 4, 5, 7, 9, 10},
target: 0,
isLeft: true,
},
want: 0,
},
{
name: "第二次测试",
args: args{
array: []int{1, 2, 2, 2, 3, 4, 4, 5, 7, 9, 10},
target: 2,
isLeft: true,
},
want: 0,
},
{
name: "第三次测试",
args: args{
array: []int{1, 2, 2, 2, 3, 4, 4, 5, 7, 9, 10},
target: 2,
isLeft: false,
},
want: 0,
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
if got := BinarySearchElement1(tt.args.array, tt.args.target, tt.args.isLeft); got < tt.want {
t.Errorf("BinarySearchElement1() = %d, want %d", got, tt.want)
}
})
}
}