二分查找

  1. 前提:该数组的元素必须有序
  2. 思想:每一次都查找中间的元素,比较大小就能减少一半的元素。
private int getIndexByElement(int[] arr, int i) {
  int left = 0;
  int right = arr.length - 1;
  while (left <= right) {
    int curr = (left + right) / 2;
    if (arr[curr] > i) {
      right = curr - 1;
    } else if (arr[curr] < i) {
      left = curr + 1;
    } else {
      return curr;
    }
  }
  return -1;
}
Copyright © rootwhois.cn 2021-2022 all right reserved,powered by GitbookFile Modify: 2022-11-26 20:03:31

results matching ""

    No results matching ""