欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

二分查找算法

程序员文章站 2022-07-12 09:16:20
...
package offer;

/**
 * 二分查找
 */
public class BinarySearch {

    public static int binarySearch(int[] a ,int v){
        int mid;
        int lo = 0;
        int hi = a.length - 1;

        while (lo <= hi){
            mid = lo + ( (hi - lo) >>> 1 );
            if (a[mid] == v){
                return mid;
            }else if (a[mid] < v){
                lo = mid + 1;
            }else{
                hi = mid - 1;
            }
        }
        return -1;

    }


    public static void main(String[] args){
        int a[] = {1,2,3,4,5,6,7,8,9};
        System.out.println(binarySearch(a,5));
    }

}