Java : Binary Search

Manish Kumar
2 min readJan 14, 2023

The binary search algorithm is an efficient algorithm for finding an element in a sorted array by repeatedly dividing the search interval in half. The basic idea behind the algorithm is to compare the value of the element in the middle of the array with the target value. If the target value is greater than the middle element, then the target value must be located in the upper half of the array, otherwise, it must be located in the lower half of the array. This process is repeated until the target value is found or the search interval is empty.

Here is an example of the binary search algorithm implemented in Java:

public 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;
} else if (arr[mid] < target) {
left = mid + 1;
} else {
right = mid - 1;
}
}
return -1;
}

In the above code, the binarySearch method takes an array and a target value as input. It initializes two pointers, left and right, to the first and last index of the array, respectively. It then enters a loop that continues as long as left is less than or equal to right. Inside the loop, it calculates the middle index of the current search interval by taking the average of left and right. It then compares the value at the middle index with the target value. If the target value is equal to the middle value, the method returns the middle index as the result. If the target value is greater than the middle value, the method updates the left pointer to be one index to the right of the middle index, effectively narrowing the search interval to the upper half of the array. If the target value is less than the middle value, the method updates the right pointer to be one index to the left of the middle index, effectively narrowing the search interval to the lower half of the array. If the target value is not found in the array, the method returns -1.

It’s important to note that the array needs to be sorted before applying the binary search algorithm.

In summary, The binary search algorithm is an efficient algorithm for finding an element in a sorted array by repeatedly dividing the search interval in half, it compares the value of the element in the middle of the array with the target

--

--