Question:
Consider the following binary search method in Java:
public static int binarySearch(int[] arr, int target) {
int left = 0;
int right = arr.length - 1;
while (left <= right) {
int middle = (left + right) / 2;
if (arr[middle] == target) {
return middle;
}
else if (arr[middle] < target) {
left = middle + 1;
}
else {
right = middle - 1;
}
}
return -1;
}
Given the sorted array int[] arr = {1, 4, 7, 10, 14, 19, 21, 27, 30}
and the target value target = 14
, apply the binary search method and determine the index at which the target value is found. If the target value is not found in the array, return -1.
Answer with Step-by-Step Explanation:
To apply the binary search method to find the target value 14 in the given sorted array, int[] arr = {1, 4, 7, 10, 14, 19, 21, 27, 30}
, we follow these steps:
Step 1: Initialize the variables left and right. Set left = 0
and right = arr.length - 1
. In this case, left = 0
and right = 8
.
Step 2: Calculate the middle index as middle = (left + right) / 2
. The middle index is (0 + 8) / 2 = 4
.
Step 3: Check if the value at the middle index (arr[middle]
) is equal to the target value 14. In this case, arr[4] = 14
, which is equal to the target value. Therefore, return the middle index 4.
The target value 14 is found at index 4.
Answer:
The index at which the target value 14 is found in the given array is 4.