java 二分法查找

时间:2022-03-04 00:00:23
package com.test;

import java.util.Arrays;

public class BinaraySearch {
    
    public static int search(int key, int[] a) {
        int lo = 0;
        int hi = a.length - 1;
        while (lo <= hi) {
            int mid = lo + (hi - lo) / 2;
            
            if (key < a[mid]) {
                hi = mid - 1;
            } else if (key > a[mid]) {
                lo = mid + 1;
            } else {
                return mid;
            }
        }
        return -1;
    }
    
    public static void main(String[] args) {
        int[] a = new int[] {2,3,19,29,40,11,12,14};
        // 数组必须是有序的
        Arrays.sort(a);
        System.out.println(search(14, a));
    }
        
}