1.Java实现
public static int binarySearch(int[] array, int key) {
int low = 0, high = array.length - 1;
while (low <= high) {
int mid = (low + high) / 2;
if (array[mid] > key) {
high = mid - 1;
} else if (array[mid] < key) {
low = mid + 1;
} else {
return mid;
}
}
return -1;
}
public static int binarySearch(int[] array, int key, int low, int high) {
int mid = (low + high) / 2;
if (array[mid] > key) {
high = mid - 1;
if (low > high) {
return -1;
}
return binarySearch(array, key, low, high);
} else if (array[mid] < key) {
low = mid + 1;
if (low > high) {
return -1;
}
return binarySearch(array, key, low, high);
} else {
return mid;
}
}
2.Golang实现
package main
import (
"fmt"
)
func main() {
a := []int{1, 3, 4, 5, 6}
key := 7
i := BinarySearch(a, 0, len(a)-1, key)
fmt.Println(key, "is:", "array[", i, "]")
}
/*
return -1 : not find & illeage bounds
return index : find key
*/
func BinarySearch(a []int, left int, rigth int, key int) int {
if left > rigth {
return -1
}
mid := (left + rigth) / 2
if a[mid] > key {
return BinarySearch(a, left, mid-1, key)
}
if a[mid] < key {
return BinarySearch(a, mid+1, rigth, key)
}
return mid
}