基本思路都一样,只是非递归在效率上可能会更高一些
package humorousz.test.com;
public class BinarySearchDemo {
public static void main(String[] args) {
int [] a=new int[]{1,2,3,4,5,6,7,8,9};
int res = binarySearch(a,0);
int res2 = binarySerach2(a,0);
System.out.println(res);
System.out.println(res2);
}
public static int binarySearch(int[] array,int aim){
int begin = 0;
int end = array.length;
int cur = -1;
while(begin < end){
int mid = (begin + end) / 2;
if(aim == array[mid]){
cur = mid ;
break;
}else if(array[mid] < aim){
begin = mid+1;
continue;
}else {
end = mid -1;
continue;
}
}
return cur;
}
private static int binarySerach2(int[] array,int aim) {
return binarySearch(array, 0, array.length, aim);
}
private static int binarySearch(int[] array,int begin,int end,int aim){
if(begin >= end)
return -1;
int mid = (begin + end)/2;
if(array[mid] == aim){
return mid;
}else if(array[mid] < aim) {
return binarySearch(array, mid+1, end, aim);
}else {
return binarySearch(array, begin, mid-1, aim);
}
}
}