首页 > 代码库 > Java实现二分法查找数组

Java实现二分法查找数组

public class binarySearchTest{    public static void main(String[] args)     {        int[] a = {1,5,9,36,49,89,102};        int c = 49;        int pos = binarySearch(a,c);        System.out.println(pos);    }    private static int binarySearch(int[] a, int c)    {        if(a.length == 0) return -1;        int start = 0;        int end = a.length - 1;        int middle = (start + end) / 2;        while(start <= end)        {            if(a[middle] == c) return middle;            if(a[middle] < c)            {                start = middle + 1;            }            else            {                end = middle - 1;            }            middle = (start + end) / 2;        }        return -1;    }}

 

Java实现二分法查找数组