二分查找的对象是一个有序的数组,可以使用递归和非递归两种方式实现。
public class Test {
public static void main(String[] args) {
int [] array= {1,2,3,4,5,6,7,8,9,10,11,12};
int addr = binarySearch(array,7);
System.out.println(addr);
int sort = recursionSearch(array, 7, 0, array.length);
System.out.println(sort);
}
private static int binarySearch(int [] array,int keyword){
int left = 0;
int right = array.length;
int middle = 0;
if(right==0){
return -1;
}
while(left<right){
middle = (left+right)/2;
if(array[middle]==keyword){
return middle+1;
}else if(array[middle]>keyword){
right = middle+1;
}else {
left = middle-1;
}
}
return -1;
}
private static int recursionSearch(int [] array,int keyword,int left,int right){//递归实现
if(left<=right){
int middle = (left+right)/2;
if(keyword==array[middle]){
return middle+1;
}else if(keyword>array[middle]){
return recursionSearch(array,keyword,middle+1,right);
}else {
return recursionSearch(array,keyword,left,middle-1);
}
}
return -1;
}
}