Post

Created by @nathanedwards
 at October 31st 2023, 10:04:20 pm.

AP Computer Science Exam Question:

You are given a sorted array of integers and a target value. Write a method called binarySearch to search for the target value using the binary search algorithm.

The method should take in the following parameters:

  • arr: an array of integers in ascending order.
  • target: the value to be searched for.

The method should return the index of the target value if it is found in the array. If the target value is not present, return -1.

public class BinarySearch {

    public static int binarySearch(int[] arr, int target) {
        int left = 0;
        int right = arr.length - 1;

        while (left <= right) {
            int mid = left + (right - left) / 2;

            if (arr[mid] == target) {
                return mid;
            }

            if (arr[mid] < target) {
                left = mid + 1;
            } else {
                right = mid - 1;
            }
        }

        return -1;
    }

    public static void main(String[] args) {
        int[] arr = {1, 3, 5, 7, 9, 11, 13};
        int target1 = 7;
        int target2 = 8;

        int index1 = binarySearch(arr, target1);
        int index2 = binarySearch(arr, target2);

        System.out.println("Target 7 found at index: " + index1); // Output: Target 7 found at index: 3
        System.out.println("Target 8 found at index: " + index2); // Output: Target 8 found at index: -1
    }
}

Explanation:

The binarySearch method uses the binary search algorithm to search for the target value in a sorted array. It initializes two pointers, left and right, to the start and end of the array, respectively.

The method then enters a while loop, which continues as long as left is less than or equal to right. Inside the loop, it calculates the middle index mid using the formula left + (right - left) / 2.

If the middle element of the array arr[mid] is equal to the target value, the method returns mid, indicating that the target value has been found.

If arr[mid] is less than the target value, the method updates left to mid + 1, effectively discarding the left half of the array.

If arr[mid] is greater than the target value, the method updates right to mid - 1, effectively discarding the right half of the array.

If the while loop completes without finding the target value, the method returns -1, indicating that the target value is not present in the array.

In the main method, we create an array arr with some values and define two target values, target1 and target2. We then call the binarySearch method to search for these targets in the array. Finally, we print the results of the search. In this example, target 7 is found at index 3, while target 8 is not present in the array, resulting in an index of -1.