public class Test {
/**
* @param int[] a 要查询的数组
* @param b 需要查询数据
*/
public static int binarySearch(int[] a , int num){
int startIndex = 0;
int endIndex = a.length-1;
if(a.length == 0){
return -1;
}
while(startIndex <= endIndex){
int middleIndex = (startIndex + endIndex) / 2;
if(a[middleIndex] == num){
return middleIndex;
}else if(a[middleIndex] > num) {
System.out.print("查询记录" + a[middleIndex] + "、");
//如果中间值比待查询的值大,则将尾部索引-1 重新赋予中间索引
endIndex = middleIndex -1 ;
}else if (a[middleIndex] < num){
System.out.print("查询记录" + a[middleIndex] + "、");
//如果中间值比待查询的值小,则将起始所引+1重新赋予中间索引
startIndex = middleIndex + 1;
}
}
return -1;
}
public static void main(String[] args) {
int[] a = {2,3,4,8,10,14,19,31,56};
System.out.println(binarySearch(a,56));
System.out.println(binarySearch(a,1)); //不存在
}
}
【算法练习】二分法查询
最新推荐文章于 2019-04-29 14:26:41 发布