二分查找

**
 * @Author: Kerven Han
 * @Date: 2020/7/23 9:39
 * @Describe:
 */
public class BinarySearch {


     public static void main(String[] args) {

         int[] arr  = {1,2,3,222,3333,8888,19023};

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


     }

         public static  int binarySearch(int[] arr,int target){

            int left = 0;
            int right = arr.length - 1;
            int mid;

            if( target > arr[right] || target < arr[left] || left > right ){
                return  -1;
            }

            while ( left <= right ){
                //这里的mid是在不断的变化的
//这里这么操作是为了防止可能的溢出
                mid = left + (right - left)/2;
                if(arr[mid] > target ){
                    right = mid + 1;
                }else if (arr[mid] < target){
                    left = left + 1;
                }else {
                    return mid;
                }
            }

            return  -1;
         }


}

 

你可能感兴趣的:(算法)