Thursday, November 27, 2014

How to write a binary search

Binary search algorithm is a simple and widely used search algorithm. It works for sorted arrays. However, it is also error-prone. When I write a piece of binary search code, I usually want to check each case to make sure everything is handled. Just like below:

int BinarySearch(int s[], int len, int key) {
  int low = 0, high = len - 1;
  while (low <= high) {
    int mid = low + (high - low) / 2;  // It is not easy to take care of the overflow.
    if (s[mid] > key) {
      high = mid - 1;
    } else if (s[mid] == key) {
      return mid;
    } else {
      low = mid + 1;
    }
  }
  return -1;
}

While it is right, I need to write two comparisons in the loop. What if only one comparison can be used?

int BinarySearch(int s[], int len, int key) {
  int low = 0, high = len - 1;
  while (low + 1 < high) {
    int mid = low + (high - low) / 2;
    if (s[mid] > key) {
      high = mid - 1;
    } else {
      low = mid;
    }
  }
  // We need to test both low and high, as both of them may be the result.
  if (low < len && s[low] == key)
    return low;
  if (high >= 0 && s[high] == key)
    return high;
  return -1;
}

But I just read a piece of binary search code written in <Beautiful code>, as below.

int BinarySearch(int s[], int len, int key) {
  int low = -1, high = len;
  while (low + 1 < high) {
    int mid = low + (high - low) / 2;
    if (s[mid] > key) {
      high = mid;
    } else {
      low = mid;
    }
  }
  // We only need to test for low, because high is always above result.
  if (low != -1 && s[low] == key) {
    return low;
  }
  return -1;
}

Of course, all of the three can be used, and have little difference with each other. But it may be fun to compare them.

No comments:

Post a Comment