编程语言
首页 > 编程语言> > 用java实现二分查找

用java实现二分查找

作者:互联网

/**

*调用erfen方法,输入数据int[] s= {0,1,2,3,4,5}和8,输出方法的返回值

*/

public class Erfen {
public int search(int[] nums, int target) {
int l=0;
int r=nums.length-1;
while(l<=r) {
int m=(l+r)/2;
if(nums[m]==target)
return m;
if(nums[m]>target)
r=m-1; //左区间
else
l=m+1;//右区间
}
return -1;
}
public static void main(String[] args) {
Erfen ee =new Erfen();
int[] s= {0,1,2,3,4,5};
int ss=8;
System.out.println(ee.search(s, ss));
}
}

标签:二分,java,target,nums,int,Erfen,ee,查找,public
来源: https://www.cnblogs.com/zcl789456/p/16637896.html