首页 > 编程语言 >最简单的算法- 二分查找

最简单的算法- 二分查找

时间:2022-10-08 21:09:10浏览次数:49  
标签:二分 src int lo mid long System 算法 查找


java代码

/**
* Created by fupeng on 2017/1/11.
*/
public class binarySearch

public static long binarySearch_a(long [] src, int key){
int lo = 0;
int hi = src.length-1;
while(lo <= hi){
int mid = lo + (hi-lo)/2;
if(key < src[mid]){
hi = mid-1;
}else if(key > src[mid]){
lo = mid+1;
}else{
return mid;
}
}

return -1;
}
public static void main(String [] argv){
System.out.println("hello world");
long [] src = {1,2,4,67,89,100,291};
for (long a : src){
System.out.println(a);
}

long find = binarySearch_a(src, 292);
if(find < 0) {
System.out.println("not found");
}else{
System.out.println(" found");
}
}
}

二分查找的条件是 : 有序的列表


标签:二分,src,int,lo,mid,long,System,算法,查找
From: https://blog.51cto.com/u_15815563/5738692

相关文章