Binary Search Recursion

/* Driver */
void main() {
  List<int> list = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9];

  int low = 0;
  int high = list.length - 1;

  assert(binarySearch(list, low, high, 5) == 5);
  assert(binarySearch(list, low, high, 9) == 9);
  assert(binarySearch(list, low, high, 66) == -1);
}

/**
 * Return the index of [key] value in [list]
 */
int binarySearch(List<int> list, int low, int high, int key) {
  if (low > high) {
    return -1; /* not found */
  }
  int mid = (low + high) >> 1;
  if (key == list[mid]) {
    return mid; /* found */
  } else if (key > list[mid]) {
    return binarySearch(
        list, mid + 1, high, key); /* search in range[mid + 1, high] */
  } else {
    return binarySearch(
        list, low, mid - 1, key); /* search in range[low, mid - 1] */
  }
}
Algerlogo

Β© Alger 2022

About us

We are a group of programmers helping each other build new things, whether it be writing complex encryption programs, or simple ciphers. Our goal is to work together to document and model beautiful, helpful and interesting algorithms using code. We are an open-source community - anyone can contribute. We check each other's work, communicate and collaborate to solve problems. We strive to be welcoming, respectful, yet make sure that our code follows the latest programming guidelines.