public class BinarySearch {
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
int[] arr=new int[]{1,2,3,5,6,7,8};
System.out.println(binarySch(arr,4));
}
public static int binarySch(int[] arr,int key){
int min=0,max=arr.length-1,mid;
while(min<=max){
mid=(min+max)>>1;
if(key<arr[mid])
max=mid-1;
else if(key>arr[mid])
min=mid+1;
else
return mid;
}
return min;
}
}
|
|