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:
left and right, to the first and last indices of the array, respectively.left is less than or equal to right:
mid by taking the average of left and right.mid is equal to the target:
mid as the index of the target element.right to mid - 1 to continue searching in the left half of the array.left to mid + 1 to continue searching in the right half of the array.In our example, the initial values of left and right are 0 and 9 respectively:
left = 0right = 9After 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 = 5right = 9After 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 = 5right = 6After 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.