一维数组二分查找

public class BinarySearch {

    public static void main(String[] args) {
        int[] arr={1,2,3,4,5,6,7,8};
        int result = binarySearch(arr,2);
        System.out.println(result);
    }
    public static int binarySearch(int[] array, int key)  
        {  
            int low = 0;  
            int high = array.length - 1;  
            int middle = 0;  
            while (low <= high)  
            {  
                middle = (low + high) / 2;  
                int middleValue = array[middle];  
                if (middleValue < key)  
                {  
                    low = middle + 1;  
                }  
                else if (middleValue > key)  
                {  
                    high = middle - 1;  
                }  
                else 
                {  
                    return middle;  
                }  
            }  
            return -1;  
        }

}

你可能感兴趣的:(一维数组二分查找)