luoheng
8/27/2019 - 11:11 AM

折半查找

// BinarySearch for value in sorted A
func BinarySearch(A []int, value int) int {
	low, high := 0, len(A)-1
	for low < high {
		mid := low + (high - low) >> 1
		if A[mid] > value {
			high = mid
		} else if A[mid] < value {
			low = mid + 1
		} else {
			return mid
		}
	}
	return -1
}