Post

Created by @nathanedwards
 at November 3rd 2023, 9:08:23 pm.

Question:

A binary search is an efficient algorithm used to search for a specific element in a sorted array. The algorithm repeatedly divides the array in half and checks if the middle element is equal to the target element. If it is, the search is successful; otherwise, the search continues in the left or right half of the array, depending on whether the target element is smaller or larger than the middle element.

Consider the following array: [2, 4, 6, 8, 10, 12, 14, 16, 18, 20]

Implement the binary search algorithm to find the position of the target element 12. Write a Java method named binarySearch that takes in an integer array arr and an integer target as parameters. The method should return the index of the target element if found, otherwise, it should return -1.

Your implementation of the binarySearch method should have the following signature:

public static int binarySearch(int[] arr, int target)

Example:

int[] arr = {2, 4, 6, 8, 10, 12, 14, 16, 18, 20};
int target = 12;
int result = binarySearch(arr, target);
System.out.println(result);  // Output: 5

Explanation:

The binary search algorithm works by repeatedly dividing the array in half. Here are the step-by-step instructions for finding the position of the target element 12 in the given array:

  1. Initialize two pointers, left and right, to the first and last indices of the array, respectively.
  2. Repeat the following steps as long as left is less than or equal to right:
    • Calculate the middle index as mid by taking the average of left and right.
    • Check if the element at index mid is equal to the target:
      • If it is equal, return mid as the index of the target element.
      • If it is greater than the target, update right to mid - 1 to continue searching in the left half of the array.
      • If it is less than the target, update left to mid + 1 to continue searching in the right half of the array.
  3. If the target element is not found after the above steps, return -1.

In our example, the initial values of left and right are 0 and 9 respectively:

  • left = 0
  • right = 9

After the first iteration, mid is calculated as (0 + 9) / 2 = 4. The element at index 4 is 10, which is less than the target 12. Therefore, we update left to mid + 1:

  • left = 5
  • right = 9

After the second iteration, mid is calculated as (5 + 9) / 2 = 7. The element at index 7 is 16, which is greater than the target 12. Therefore, we update right to mid - 1:

  • left = 5
  • right = 6

After the third iteration, mid is calculated as (5 + 6) / 2 = 5. The element at index 5 is 12, which is equal to the target. Therefore, we return mid as the index of the target element: 5.