思想:根据中间值缩小数组一般长度进行查找数据
public class ErFenChaZhao
{
public static void main(String[] args)
{
int[] arr={10,20,30,40};
System.out.println(getIndexByELE(arr,20)+1);
}
private static int getIndexByELE(int[] arr,int ele){
int minIndex=0;
int maxIndex=arr.length-1;
int centerIndex=(minIndex+maxIndex)/2;
while(minIndex<=maxIndex){
if(ele==arr[centerIndex]){
return centerIndex;
}
else if(ele>arr[centerIndex]){
minIndex=centerIndex+1;
}
else if(ele<arr[centerIndex])
{
maxIndex=centerIndex-1;
}
//重新计算
centerIndex=(minIndex+maxIndex)/2;
}
return 0;
}
}