package main
import "fmt"
// 查找第一个值等于给定值的元素
func BinarySearchFirstEqual(array []int, target int) int {
low, high := 0, len(array)-1
for low <= high {
mid := low + (high-low)/2
if array[mid] < target {
low = mid + 1
} else if array[mid] > target {
high = mid - 1
} else {
if mid == 0 || array[mid-1] != target {
return mid
} else {
high = mid - 1
}
}
}
return -1
}
// 查找最后一个值等于给定值的元素
func BinarySearchLastEqual(array []int, target int) int {
low, high := 0, len(array)-1
for low <= high {
mid := low + (high-low)/2
if array[mid] < target {
low = mid + 1
} else if array[mid] > target {
high = mid - 1
} else {
if mid == len(array)-1 || array[mid+1] != target {
return mid
} else {
low = mid + 1
}
}
}
return -1
}
// 查找第一个大于等于给定值的元素
func BinarySearchFirstLargeEqual(array []int, target int) int {
low, high := 0, len(array)-1
for low <= high {
mid := low + (high-low)/2
if array[mid] < target {
low = mid + 1
} else {
if mid == 0 || array[mid-1] < target {
return mid
} else {
high = mid - 1
}
}
}
return -1
}
// 查找最后一个小于等于给定值的元素
func BinarySearchLastSmallEqual(array []int, target int) int {
low, high := 0, len(array)-1
for low <= high {
mid := low + (high-low)/2
if array[mid] <= target {
if mid == len(array)-1 || array[mid+1] > target {
return mid
} else {
low = mid + 1
}
} else {
high = mid - 1
}
}
return -1
}
func main() {
test := []int{1, 3, 7, 9, 9, 9, 10, 15, 17, 17, 20}
fmt.Println(BinarySearchLastEqual(test, 9))
}