java基础之二分查找

Posted 暮尘时雨

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了java基础之二分查找相关的知识,希望对你有一定的参考价值。

一、

public class BinarySeachTest {
public static void main(String[] args) {
    int[] arr = new int[]{22,54,88,97,105,112};
    System.out.println(binarySeach(arr, 112));
}
/**
 *
 * @return 返回传入的value在数组位置
 */
public static int binarySeach(int[] num,int value){
    int start=0;  //数组的开始下标
    int end =num.length-1;  //数组的结尾下标
    while(start<=end){
        int middle = (start+end)/2;  //中间位置
        if(num[middle]>value){
            end=middle-1;
        }else if(num[middle]<value){
            start=middle+1;
        }else {
            return middle;
        }
    }
    return -1;
}

}

以上是关于java基础之二分查找的主要内容,如果未能解决你的问题,请参考以下文章