Implement Binary Search Algorithm in Java


Write a Java Program to implement Binary Search Algorithm.

Click Here to View the Solution!
import java.util.Scanner;

public class BinarySearch {
    int binarySearch(int array[], int element, int low, int high) {
        // loop iterates until low and high meet
        while (low <= high) {
            // calculating index of midpoint
            int mid = low + (high - low) / 2;
            // if mid element = required element
            if (array[mid] == element)
                return mid;
            // if element < mid element , search left only
            if (array[mid] < element)
                low = mid + 1;
            // if element > mid element, search right only
                high = mid - 1;
        return -1;
    public static void main(String args[]) {
        // create an object of Main class
        BinarySearch obj = new BinarySearch();
        // create a sorted array
        int[] array = { 13, 54, 5, 16, 7, 18, 9,99 };
        int n = array.length;
        // get input from user for element to be searched
        Scanner input = new Scanner(;
        System.out.println("Enter element to be searched:");
        // element to be searched
        int element = input.nextInt();
        // call the binary search method       
        // pass arguments: array, element, index of first and last element
        int result = obj.binarySearch(array, element, 0, n - 1);
        if (result == -1)
            System.out.println("Not found");
            System.out.println("Element found at index number " + result);
Click Here to View the Output!
Enter element to be searched:
 Element found at index number 3
Click Here to View the Explanation!
  • This program is used to perform the implementation of the binary search algorithm.
  • A binarySearch() method is initialized to store the index of the mid element in mid.
  • A nested if…else statement is used to find the entered element. It is first compared to the mid value. And if it is true, it returns the index of mid.
  • If false and the element is less than the mid value, it is compared to all the elements on the left of mid and if found, the index of that element is returned.
  • Else, if the element is greater than the mid value, the element is compared with all the elements on the right of mid and if found, the index of that element is returned.
  • In main(), an integer array is initialized as { 13, 54, 5, 16, 7, 18, 9,99 } and an element is requested to be entered by the user through the Java Scanner Class.
  • Finally, the binarySearch algorithm is applied on the entered element and its index is displayed on the screen.