package main
import "fmt"
func binarySearch(arr []int ,val int)int {
left := 0;
right:=len(arr)-1;
for left<right {
mid := (left+right)>>1
if arr[mid]==val {
return mid
}else if arr[mid]>val {
right = mid-1;
}else {
left = mid+1
}
}
return -1;
}
//二分搜索数组中最后一个元素,数组分成两半,右侧是大于查找值,左右小于等于查找值。不停更新左侧,逼近右侧,同时右侧也在迭代中,最终左侧迭代到值和left相等。
func binaryLastSearch(arr []int, val int) int {
left := 0
right := len(arr) - 1
for left < right {
mid := (right+left)>>1
if arr[mid]>val{
right = mid-1
}else{
left = mid
}
}
if arr[left]==val {
return left;
}
return -1;
}
//和查找第一个类似,因为查找第一个,必须分成两半,左右小于,右侧保证大于等于,同样这里右侧如果右重复,右侧不断迭代到第一个相等
func binaryFirstSearch(arr []int,val int)int {
left := 0
right:=len(arr)-1
for left<right {
mid := (left+right)>>1
if arr[mid] < val {
left = mid + 1
}else{
right = mid
}
}
if arr[left] == val {
return left;
}
return -1;
}
func main() {
arr := []int{1,2,3,4,4,4,4,5,6}
fmt.Println(binarySearch(arr,4))
fmt.Println(binaryLastSearch(arr,4))
fmt.Println(binaryFirstSearch(arr,4))
}
网友评论