Skip to content
Related Articles

Related Articles

Binary Search in Java

Improve Article
Save Article
Like Article
  • Difficulty Level : Easy
  • Last Updated : 28 Nov, 2021

Binary search is one of the searching techniques applied when the input is sorted as here we are focusing on finding the middle element that acts as a reference frame whether to go left or right to it as the elements are already sorted. This searching helps in optimizing the search technique with every iteration is referred to as binary search and readers do stress over it as it is indirectly applied in solving questions. Now you must be thinking what if the input is not sorted then the results are undefined.

Note: If there are duplicates, there is no guarantee which one will be found.

Now let us adhere to the significant value of the negative value returned by both functions

The function returns an index of the search key, if it is contained in the array; otherwise, (-(insertion point) – 1). The insertion point is defined as the point at which the key would be inserted into the array: the index of the first element greater than the key, or a.length if all elements in the array are less than the specified key. Note that this guarantees that the return value will be >= 0 if and only if the key is found.

Implementation of Binary Search in Java 

Java




// Java implementation of recursive Binary Search
class BinarySearch
{
    // Returns index of x if it is present in arr[l..
    // r], else return -1
    int binarySearch(int arr[], int l, int r, int x)
    {
        if (r>=l)
        {
            int mid = l + (r - l)/2;
  
            // If the element is present at the
            // middle itself
            if (arr[mid] == x)
               return mid;
  
            // If element is smaller than mid, then
            // it can only be present in left subarray
            if (arr[mid] > x)
               return binarySearch(arr, l, mid-1, x);
  
            // Else the element can only be present
            // in right subarray
            return binarySearch(arr, mid+1, r, x);
        }
  
        // We reach here when element is not present
        //  in array
        return -1;
    }
  
    // Driver method to test above
    public static void main(String args[])
    {
        BinarySearch ob = new BinarySearch();
        int arr[] = {2,3,4,10,40};
        int n = arr.length;
        int x = 10;
        int result = ob.binarySearch(arr,0,n-1,x);
        if (result == -1)
            System.out.println("Element not present");
        else
            System.out.println("Element found at index " +
                                                 result);
    }
}
Output: 
Element found at index 3

 

Tip: Geeks you must be wondering out whether there is any function like lower_bound() or upper_bound() just likely found in C++ STL. so the straight answer is that there was no function only till Java 9, later onwards they were added. 

Types of Binary Search in Java

There are two ways to do a binary search in Java

  • Arrays.binarysearch
  • Collections.binarysearch

Type 1: Arrays.binarysearch() 

It works for arrays which can be of primitive data type also.

Example:

Java




// Java Program to demonstrate working of binarySearch()
// Method of Arrays class In a sorted array
 
// Importing required classes
import java.util.Arrays;
 
// Main class
public class GFG {
 
    // Main driver method
    public static void main(String[] args)
    {
        // Declaring an integer array
        int arr[] = { 10, 20, 15, 22, 35 };
 
        // Sorting the above array
        // using sort() method od Arrays class
        Arrays.sort(arr);
 
        int key = 22;
        int res = Arrays.binarySearch(arr, key);
 
        if (res >= 0)
            System.out.println(
                key + " found at index = " + res);
        else
            System.out.println(key + " Not found");
 
        key = 40;
        res = Arrays.binarySearch(arr, key);
        if (res >= 0)
            System.out.println(
                key + " found at index = " + res);
        else
            System.out.println(key + " Not found");
    }
}
Output: 
22 found at index = 3
40 Not found

 

Now let us see how does Collections.binarySearch() work for LinkedList. So basically as discussed above this method runs in log(n) time for a “random access” list like ArrayList. If the specified list does not implement the RandomAccess interface and is large, this method will do an iterator-based binary search that performs O(n) link traversals and O(log n) element comparisons.

Type 2: Collections.binarysearch() 

It works for objects Collections like ArrayList and LinkedList

Example

Java




// Java Program to Demonstrate Working of binarySearch()
// method of Collections class
 
// Importing required classes
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
 
// Main class
public class GFG {
    // Main driver method
    public static void main(String[] args)
    {
        // Creating an empty ArrayList of integer type
        List<Integer> al = new ArrayList<Integer>();
 
        // Populating the Arraylist
        al.add(1);
        al.add(2);
        al.add(3);
        al.add(10);
        al.add(20);
 
        // 10 is present at index 3
        int key = 10;
        int res = Collections.binarySearch(al, key);
 
        if (res >= 0)
            System.out.println(
                key + " found at index = " + res);
        else
            System.out.println(key + " Not found");
 
        key = 15;
        res = Collections.binarySearch(al, key);
 
        if (res >= 0)
            System.out.println(
                key + " found at index = " + res);
        else
            System.out.println(key + " Not found");
    }
}
Output: 
10 found at index = 3
15 Not found

 


My Personal Notes arrow_drop_up
Recommended Articles
Page :

Start Your Coding Journey Now!