非递归方法
public static int select(int[] arry,int num){int high=arry.length-1; int low=0; while(low<=high){ //这种方式取中间值是为了防止溢出 int mid=low+(high-low)/2; if(num<arry[mid]){ high=mid-1; } else if(num>arry[mid]){ low=mid+1; } else if(num==arry[mid]){ return mid; }
}
return -1;
}递归方法
public static int select1(int [] arry,int low,int high,int num){int mid=low+(high-low)/2; while(low<=high){ if(num==arry[mid]){ return mid; } else if(num>arry[mid]){ return select1(arry,mid+1,high,num); } else if(num<arry[mid]){ return select1(arry,low,mid-1,num); } } return -1;
}
java语言实现二分查找的两种方法
猜你喜欢
转载自blog.csdn.net/ocean_java666/article/details/81174240
今日推荐
周排行