package mytest;
public class test {
public static int BinarySearch(int low,int high,int[]arr,int x){
int loc=-1;
while(low<=high){
int mid=(low+high)/2;
if(x==arr[mid]){loc=mid;break;}
else if(x<arr[mid])
{high=mid-1;}
else {low=mid+1;}
}
return loc;
}
public static void main(String[]args){
int[]myArr={1,2,3,4,5,6};
int loc=-1;
loc=BinarySearch(0,myArr.length-1,myArr,15);
if(loc==-1){System.out.println("Not found");}
else{System.out.println("Find it!location is:"+loc);}
}
}
递归算法:
package mytest;
public class test {
public static int BinarySearch(int low,int high,int[]arr,int x,int loc){
if((low<=high)&&(loc==-1)){
int mid=(low