/**
* 二分查找
*/
package com.test1;
public class Demo5_4 {
public static void main(String[] args) {
int arr[]={2,3,5,7,8};
BinaryFind bf=new BinaryFind();
bf.find(0, arr.length-1, 7, arr);
}
}
class BinaryFind
{
public void find(int leftIndex,int rightIndex,int val,int arr[])
{
//首先找到中间的数
int midIndex=(rightIndex+leftIndex)/2;
int midVal=arr[midIndex];
if(rightIndex>=leftIndex){
//如果要找的数比midVal大
if(midVal>val){
//在arr左边数中找
find(leftIndex,midIndex-1,val,arr);
}else if(midVal<val)
{
//在arr的右边找
find(midIndex+1,rightIndex,val,arr);
}else if(midVal==val)
{
System.out.println("找到下标"+midIndex);
}
}
}
}