Processing math: 100%

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. Θ(n) / Θ(1)
  2. Ω(n) / Ω(1)
  3. Θ(n) / Θ(log2n)
  4. Θ(log2n) / Θ(1)
  5. Ω(log2n) / Ω(1)
  6. Θ(log2n) / Θ(log2n)
  7. Ω(log2n) / Ω(log2n)