算法实现收藏-数组中检索查找

  static final int[] array = {0, 1,8,20,34,50};
  static int size = array.length;
  static int search = 1;
 
 //1.二分法查找某个数字所在的位置,前提是数组必须是有序的
 static void binarySearchMax()
  {
    int low = 0, hight = size - 1;
    int index = 0,count = 0;
    A:while (true) {
      index = (low + hight) / 2;
      count++;
      if (search < array[index]) {
        hight = index;
      } else if (search > array[index]) {
        low = index;
      } else {
        out.println("关键字所在的索引为:" + index);
        out.println("查找次数:" + count);
        break A;
      }
    }
  }

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