Solution to binary search practice problem

Complete the Binary search practice problem before viewing the solution.

Review the binary search practice problem with AP CS Tutor Brandon Horn.

public static int binarySearch(int[] x, int key)
{
 return binarySearch(x, key, 0, x.length - 1);
}

private static int binarySearch(int[] x, int key, int start, int end)
{
  if (start > end)
    return -start - 1;

  int mid = (start + end) / 2;
  int result = key - x[mid];

  if (result < 0)
    return binarySearch(x, key, start, mid - 1);
  else if (result > 0)
    return binarySearch(x, key, mid + 1, end);
  else
    return mid;
}

Get AP CS Help

Leave a Reply