package com.datastack.search;

/**

 * 二分查找

 */

public class BinarySearch {

    public static void main(String[] args) {

        int[] arr = new int[]{1,2,3,4,5,6,7,8,9};

        System.out.println(binarySearch(arr, 9));

    }

    public static int binarySearch(int[] array,int key){

        int low = 0;

        int hight = array.length -1;

        int middle = 0;

        while(low<=hight){

            middle=(low+hight)/2;

            int value = array[middle];

            if(value>key){

                hight = middle-1;

            }else if(value<key){

                low = middle+1;

            }else{

                return middle;

            }

        }

        return -1;

    }

}