最基本的二分查找法、不考虑数组有重复数据、匹配到返回具体元素、没有返回-1
public class TestBinary {
public int binarySearch(int[] array, int key){
int left = 0;
int right = array.length -1;
while (left <= right){
int mid = (left+right)/2;
if (array[mid] == key){
return array[mid];
}else if (array[mid] < key){
left = mid +1;
}else {
right = mid -1;
}
}
return -1;
}
public static void main(String[] args) {
int[] a = {10,20,30,40,50};
int i = new TestBinary().binarySearch(a, 10);
System.out.println("i = " + i);
}
}