Home » Java Tutorial » Binary Search Java with Examples

Binary Search Java with Examples

A binary search java is a searching technique to search the element from the given set of data. For binary search, data must be in sorted order. In this method, a set of data is divided into two parts and compares the search element with the middle element. When the search element and the middle element are the same, then a search is terminated.

If the search element is less than the middle element, then the search process is continued on the data set’s left side.

If the search element is greater than the middle element, then the search process is continued on the data set’s right side.

This process continues until the search element is found or the search element is not in the data set.

How to do binary search in java?

To do a java binary search, accept an array from the user. Also, accept elements to be searched in that array. Write a function for binary search in java. Pass accepted array and the search element to the function. If the search element is present in the array, the function will return that element, or the function will give output as an element not found if the search element is not present in the array.

Binary search algorithm

Algorithm for binary search in java.

  1. Accept array from user
  2. Accept search element from the user
  3. Compare the search element with the middle element of an array.
  4. If the search element is less than the middle element, search the element in the left part of an array.
  5. If the search element is greater than the middle element, search the element in the right part.

Binary search example in java

There are three ways to implement the binary search algorithm in java. Let’s understand it one by one.

1. Binary search in java using for loop.

Use the algorithm of binary search in for loop and perform the searching operation on a sorted array. The algorithm will return the value to be searched if it is present in the array.

Example

import java.util.Scanner;

public class binary 
{    
    int binarysearch(int array[], int element, int low, int high)
    {
        while (low <= high) 
        {
            int mid = low + (high - low) / 2;
            if (array[mid] == element)
              return mid;
            if (array[mid] < element)
              low = mid + 1;
            else
              high = mid - 1;
        }   
        return -1;
    }
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        binary obj = new binary();
        
        System.out.println("Enter number of elements:");
        int num = sc.nextInt();
        int array[] = new int[num];
        System.out.println("Enter data in sorted order");
        for (int i = 0; i < num; i++) {
            System.out.println("Enter data");
            array[i] = sc.nextInt();
        }
        System.out.print("Array is : ");
        for (int i = 0; i < array.length; i++) {
            System.out.print(array[i]);
        }
        
        System.out.println("\nEnter an element to be searched : ");
        int n = sc.nextInt();
        
        int result = obj.binarysearch(array, n, 0, n - 1);
        if (result == -1)
            System.out.println("Not found");
        else
            System.out.println("Element found at index " + result);
    }

}

Output

Enter number of elements:
5
Enter data in sorted order
Enter data
1
Enter data
2
Enter data
3
Enter data
4
Enter data
5
Array is : 12345
Enter an element to be searched : 
3
Element found at index 2

2. Binary search in java using recursion.

The same logic of binary search is used in the binary search recursive program. Create a recursive function for searching.

Example

import java.util.Scanner;

public class binary 
{    
    int binarysearch(int array[], int element, int low, int high)
    {
       if (high >= low) 
       {
            int mid = low+ (high - low) / 2;
            if (array[mid] == element)
            return mid;
            if (array[mid] >element)
            return binarysearch(array, low, mid - 1, element);

            return binarysearch(array, mid + 1, high, element);
        }
return -1;
}
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        binary obj = new binary();
        
        System.out.println("Enter number of elements:");
        int num = sc.nextInt();
        int array[] = new int[num];
        System.out.println("Enter data in sorted order");
        for (int i = 0; i < num; i++) {
            System.out.println("Enter data");
            array[i] = sc.nextInt();
        }
        System.out.print("Array is : ");
        for (int i = 0; i < array.length; i++) {
            System.out.print(array[i]+"\t");
        }
        
        System.out.println("\nEnter an element to be searched : ");
        int n = sc.nextInt();
        
        int result = obj.binarysearch(array, n, 0, n - 1);
        if (result == -1)
            System.out.println("Not found");
        else
            System.out.println("Element found at index " + result);
    }

}

Output

Enter number of elements:
5
Enter data in sorted order
Enter data
2
Enter data
3
Enter data
4
Enter data
5
Enter data
6
Array is : 23456
Enter an element to be searched : 
3
Element found at index 1

3. Java binary search using binarySearch() function.

An array class provides a binarySearch named function. Using it we can also search an element.

Example

import java.util.Arrays;
import java.util.Scanner;

public class binary 
{    
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        binary obj = new binary();
        
        System.out.println("Enter number of elements:");
        int num = sc.nextInt();
        int array[] = new int[num];
        System.out.println("Enter data in sorted order");
        for (int i = 0; i < num; i++) {
            System.out.println("Enter data");
            array[i] = sc.nextInt();
        }
        System.out.print("Array is : ");
        for (int i = 0; i < array.length; i++) {
            System.out.print(array[i]+"\t");
        }
        
        System.out.println("\nEnter an element to be searched : ");
        int n = sc.nextInt();
        
        int result = Arrays.binarySearch(array, n);
        if (result == -1)
            System.out.println("Not found");
        else
            System.out.println("Element found at index " + result);
    }

}

Output

Enter number of elements:
5
Enter data in sorted order
Enter data
1
Enter data
2
Enter data
3
Enter data
4
Enter data
5
Array is : 1	2	3	4	5	
Enter an element to be searched : 
5
Element found at index 4
How to implement binary search tree in java?

A java binary tree is divided into three parts. Parent node, left child node, right child node. Accept elements from a user. The first element is a node of the tree. If the next element is less than the parent node, put it on the left side of the tree. If it is greater than the parent node, put it on the right side of the tree. Continue this process for all the elements.

Do you know?
1. Armstrong Number in Java
2. Method overloading in java
3. Prime Number Program in Java
4. Type Casting In Java
5. Ternary Operator in Java
6. Immutable Class in Java
7 . Printf Java
8. While Loop Java
9. StringBuilder java
10. Binary Search Java

Pin It on Pinterest