package search;
public class BinarySearchDemo {
public static int binarySearch(int[] a,int key) {
int min = 0;
int max = a.length -1;
int mid;
while(min<=max) {
mid = (min+max)>>1;
if(key < a[mid])
max = mid -1;
else if(key > a[mid])
min = mid +1;
else
return mid;
}
return -1;
}
public static void main(String[] args) {
int[] a = {1,2,3,4,6,8,10};
System.out.println(binarySearch(a,6));
}
}
|
|