二分查找算法

lixiaotao 2019-12-05

/**
* 二分查找算法
* @param args
*/
public static void main(String[] args) {

  int []arr = {1,2,3,4,5,6,7,8,9,10,12,14,15};

  int min = 0;
  int max = arr.length-1;
  int mid = (min + max) / 2;

  int n = 15;

  for (int i = 0; i < arr.length; i++) {
    if(arr[mid] < n) {
      min = mid + 1;
    }else if(arr[mid] > n) {
      max = mid - 1;
    }else {
      System.out.println("查找结果为:"+ arr[mid]+",下表为: "+mid);
      break;
    }
    mid = (max + min) / 2;
  }

}

相关推荐