Google News
logo
Java Program for Binary Search
In the following examples of Java program for Binary Search :
Program :
public class BinarySearch {

    public static void main(String[] args) {
        int[] arr = {2, 4, 6, 8, 10};
        int key = 8;
        int index = binarySearch(arr, key);
        if (index == -1) {
            System.out.println("Element not found in array");
        } else {
            System.out.println("Element found at index " + index);
        }
    }

    public static int binarySearch(int[] arr, int key) {
        int left = 0;
        int right = arr.length - 1;
        while (left <= right) {
            int mid = (left + right) / 2;
            if (arr[mid] == key) {
                return mid;
            } else if (arr[mid] < key) {
                left = mid + 1;
            } else {
                right = mid - 1;
            }
        }
        return -1;
    }
}
Output :
Element found at index 3
In this program, we first declare an integer array arr and initialize it with the values 2, 4, 6, 8, and 10. We also declare an integer variable key and initialize it with the value 8, which is the element we want to search for.

We then call the binarySearch method and pass the array and the key as arguments. This method performs a binary search on the array and returns the index of the first occurrence of the key, or -1 if the key is not found.

The binary search algorithm works by repeatedly dividing the search interval in half until the key is found or the interval is empty. In each iteration of the while loop, we calculate the middle index of the current interval using the formula (left + right) / 2, and compare the element at the middle index with the key. If the middle element is equal to the key, we return its index. If the middle element is less than the key, we set the left endpoint to mid + 1. If the middle element is greater than the key, we set the right endpoint to mid - 1.

Finally, we print the result of the binary search. If the index returned by the method is -1, we print "Element not found in array".

Otherwise, we print "Element found at index" followed by the index.