java 二分法查找实现

时间:2021-02-27 22:13:23
实现二分法主要有一下两种: while循环和递归。
package interview201505;public class BinarySearch {    /**     * 二分查找算法     * while循环     */    public static int binarySearch(int[] data, int find){        int low = 0;        int high = data.length-1;        while(low < high){            int mid = (low +high)/2;            if(find < data[mid]){                high = mid;            }else if(find > data[mid]){                low = mid;            }else if(find == data[mid]){                return mid;            }        }        return -1;            }    /**     * 二分法使用递归     *      */    public static int binarySearch2(int[] data, int find,int low,int high){                int mid = (low+high)/2;        if(data[mid] < find){            return binarySearch2(data,find,mid+1,high);        }else if(data[mid] > find){            return binarySearch2(data,find,low,mid-1);        }else if (data[mid] == find){            return mid;        }        return -1;    }    public static void main(String[] args){        int[] data = {1,2,3,4,5,6,7};        System.out.println(binarySearch(data, 6));        System.out.println(binarySearch2(data, 6, 0, 6));    }}