public static void main(String[] args) {
/*
* 1:定义3个变量用来标识3个角标min mid max
* 2获取中间角标mid=(min+max)/2
* 3判断要查找的值val与中间角标位置的值大小,如果大的话min=mid+1,如果小的话max=mid-1
* 4再次修改mid的值,mid=(min+max)/2,再次判断,直到要找的值等于mid所在位置的值
* 5越界判断,当max>min的时候就说明该值不存在于数组中,返回索引取负说明应该放在数组中的什么位置,但是考虑到输入0的时候返回-0还是0,所以-1
*/
int[] arr ={1,13,25,37,49,511};
System.out.println("please input the number you want to find");
Scanner sc=new Scanner(System.in);
int number = sc.nextInt();
int index = serch(arr, number);
System.out.println(number+"在数组中的索引是"+index);
}
/**
* @param arr
* @param int number
*/
public static int serch(int[] arr, int number ) {
int minIndex=0,midIndex,maxIndex=arr.length-1;
midIndex=(minIndex+maxIndex)/2;
while(number!=arr[midIndex]){
if(number>arr[midIndex]){
minIndex=midIndex+1;
}else if(number<arr[midIndex]){
maxIndex=midIndex-1;
}
if(maxIndex<minIndex){
return -midIndex-1;
}
midIndex=(minIndex+maxIndex)/2;
}
return midIndex;
}