public class BinarySearch1 {
public static void main(String[] args) {
int[]arr={1,21,31,41,51,61,71,81,91};
System.out.println(search(arr,331));
}
private static int search(int[] arr ,int key) {
int min=0;
int max=arr.length;
while (min<=max) {
int mid =(max+min)>>>1;
if (arr[mid]>key) {
max=mid-1;
}else if (arr[mid]<key) {
min=mid+1;
}else {
return mid;
}
}
return -1-min;
}
} |
|