Binary Search in an Array


/* Return the position of target in the (sorted) array values, or -1
   if the target is not in the array. */
public static int binarySearch(int[] values, int target, 
                               int start, int end) {

    if (start > end) {
        return -1;
    }

    int mid = (start + end) / 2;

    if (target == values[mid]) {
        return mid;
    } else if (target < values[mid]) {
        return binarySearch(values, target, start, mid - 1);
    } else {
        return binarySearch(values, target, mid + 1, end);
    }

}

Example:

3

5

18

22

30

31

33

37

39

50

51

54

60

62

70

93

Socrative Question

Which of the following best describe the worst case/best case performance of binary search?

  1. \(\Theta(n)\) / \(\Theta(1)\)
  2. \(\Omega(n)\) / \(\Omega(1)\)
  3. \(\Theta(n)\) / \(\Theta(\log_2 n)\)
  4. \(\Theta(\log_2 n)\) / \(\Theta(1)\)
  5. \(\Omega(\log_2 n)\) / \(\Omega(1)\)
  6. \(\Theta(\log_2 n)\) / \(\Theta(\log_2 n)\)
  7. \(\Omega(\log_2 n)\) / \(\Omega(\log_2 n)\)