package com.hai2;
public class Demo3 {
public static void main(String[] args) {
// TODO Auto-generated method stub
int arr[]={2,5,7,12,25};
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=(leftIndex+rightIndex)/2;
int midVal=arr[midIndex];
if(rightIndex>=leftIndex){
//如果要找的数比miaVal小
if(midVal>val){
//在arr左边数中找
find(leftIndex,midIndex-1,val,arr);
}else if(midVal<val)
{
//在arr右边的数找
find(leftIndex+1,midIndex,val,arr);
}else if(midVal==val)
{
System.out.println("找到下标"+midIndex);
}
}
}
} |
|