Binary search is a widely used algorithm for searching for a specific value in a sorted list of values.
The algorithm works by repeatedly dividing the search interval in half until the target value is found or it is determined that the value is not present in the list.
In Java, implementing binary search algorithm is quite easy.
Here’s a step-by-step guide on how to do it.
Create a Java Class
First, create a Java class to hold the binary search algorithm.
For example:
public class BinarySearch { // code goes here }Write a Binary Search Method
Next, write a binary search method that takes in an array of integers and the value to be searched as its parameters.
The method should return the index of the target value in the array if it exists, and -1 if it doesn’t.
Here’s an example of what the binary search method should look like:
public static int binarySearch(int[] arr, int target)
{
int left = 0;
int right = arr.length - 1;
while (left <= right) {
int mid = (left + right) / 2;
if (arr[mid] == target) {
return mid;
} else if (arr[mid] < target) {
left = mid + 1;
} else {
right = mid - 1;
}
}
return -1;}
Test the Binary Search Method
Finally, test the binary search method by creating an array of integers and calling the method with a target value.
If the method returns the correct index, it means the implementation is successful.
Here’s an example of how to test the binary search method:
public static void main(String[] args)
{
int[] arr = {1, 3, 5, 7, 9};
int target = 7;
int result = binarySearch(arr, target);
if (result == -1) {
System.out.println("Element not present");
} else {
System.out.println("Element found at index " + result);
}}
In this example, the binary search method is called with an array of integers {1, 3, 5, 7, 9} and a target value of 7.
The method returns the index of the target value, which is 3. Therefore, the output of the program is “Element found at index 3”.
In conclusion, implementing the binary search algorithm in Java is a straightforward process that involves creating a Java class, writing a binary search method, and testing the method with sample data.
By following these simple steps, you can easily implement the binary search algorithm in your Java projects.




