The Wayback Machine - https://web.archive.org/web/20241125052333/https://www.geeksforgeeks.org/binary-search-in-java/
Open In App

Binary Search in Java

Last Updated : 23 Oct, 2024
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

Binary search is one of the searching techniques applied when the input is sorted 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.

Binary-Search


Binary Search Algorithm in Java

Below is the Algorithm designed for Binary Search:

  1. Start
  2. Take input array and Target
  3. Initialise start = 0 and end = (array size -1)
  4. Intialise mid variable
  5. mid = (start+end)/2
  6. if array[ mid ] == target then return mid
  7. if array[ mid ] < target then start = mid+1
  8. if array[ mid ] > target then end = mid-1
  9. if start<=end then goto step 5
  10. return -1 as Not element found
  11. Exit

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.

Methods for Java Binary Search

There are three methods in Java to implement Binary Search in Java are mentioned below:

  1. Iterative Method
  2. Recursive Method
  3. Inbuild Method

1. Iterative Method for Binary Search  in Java

Below is the implementation is mentioned below:

Java
// Java implementation of iterative Binary Search

class BinarySearch {
    int binarySearch(int a[], int l, int r, int x)
    {
        while (l <= r) {
            int m = (l + r) / 2;

            // Index of Element Returned
            if (a[m] == x) {
                return m;

            // If element is smaller than mid, then
            // it can only be present in left subarray
            // so we decrease our r pointer to mid - 1 
            } else if (a[m] > x) {
                r = m - 1;

            // Else the element can only be present
            // in right subarray
            // so we increase our l pointer to mid + 1
            } else {
              l = m + 1;
            }  
        }

        // No Element Found
        return -1;
    }

    public static void main(String args[])
    {
        BinarySearch ob = new BinarySearch();

        int a[] = { 2, 3, 4, 10, 40 };
        int n = a.length;
        int x = 10;
      
        int res = ob.binarySearch(a, 0, n - 1, x);

        if (res == -1)
            System.out.println("Element not present");
        else
            System.out.println("Element found at index " + res);
    }
}

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. 


2. Recursive Method for Binary Search

Below is the implementation of the above method:

Java
// Java implementation of
// recursive Binary Search

class BinarySearch {
    int binarySearch(int a[], int l, int r, int x)
    {

          if (r >= l) {
            int m = l + (r - l) / 2;

            // Returned Index of the Element
            if (a[m] == x)
                return m;

            // If element is smaller than mid, then
            // it can only be present in left subarray
            if (a[m] > x)
                return binarySearch(a, l, m - 1, x);

            // Else the element can only be present
            // in right subarray
            return binarySearch(a, m + 1, r, x);
        }

        // No Element Found
        return -1;
    }

    // main function
    public static void main(String args[])
    {
        BinarySearch ob = new BinarySearch();

        int a[] = { 2, 3, 4, 10, 40 };
        int n = a.length;
        int x = 10;
      
        int res = ob.binarySearch(a, 0, n - 1, x);

        if (res == -1)
            System.out.println(
                "Element is not present in array");
        else
            System.out.println("Element is present at index " + res);
    }
}

Output
Element is present at index 3

Complexity of the above method

Time Complexity: O(log N)
Space Complexity: O(1), If the recursive call stack is considered then the auxiliary space will be O(log N)


3. In Build Method for Binary Search in Java

Arrays.binarysearch()  works for arrays which can be of primitive data type also.

Below is the implementation of the above method:

Java
// Java Program to demonstrate working of binarySearch()
// Method of Arrays class In a sorted array

import java.util.Arrays;

public class GFG {

    public static void main(String[] args)
    {

          int a[] = { 10, 20, 15, 22, 35 };

        // Sorting the above array
        // using sort() method of Arrays class
        Arrays.sort(a);

        int x = 22;
        
          int res = Arrays.binarySearch(a, x);

        if (res >= 0)
            System.out.println(x + " found at index = " + res);
        else
            System.out.println(x + " Not found");

        x = 40;
        res = Arrays.binarySearch(a, x);
          
        if (res >= 0)
            System.out.println(x + " found at index = " + res);
        else
            System.out.println(x + " Not found");
    }
}

Output
22 found at index = 3
40 Not found


Binary Search in Java Collections

Now let us see how 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.

Collections.binarysearch()  works for objects Collections like ArrayList and LinkedList

Below is the implementation of the above method: 

Java
// Java Program to Demonstrate Working of binarySearch()
// method of Collections class

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

public class GFG {
    public static void main(String[] args)
    {

          List<Integer> a = new ArrayList<Integer>();

        // Populating the Arraylist
        a.add(1);
        a.add(2);
        a.add(3);
        a.add(10);
        a.add(20);

        int x = 10;
        int res = Collections.binarySearch(a, x);

        if (res >= 0)
            System.out.println(x + " found at index = " + res);
        else
            System.out.println(x + " Not found");

        x = 15;
        res = Collections.binarySearch(a, x);

        if (res >= 0)
            System.out.println(x + " found at index = " + res);
        else
            System.out.println(x + " Not found");
    }
}

Output
10 found at index = 3
15 Not found

The complexity of the above method

Time complexity: O(log N)
Auxiliary space: O(1)




Previous Article
Next Article

Similar Reads

Java Program to Search ArrayList Element Using Binary Search
Linear Search can be implemented for sorting and non-sorting elements of a Data structure particular Data structure but the average case time complexity is O(n). Whereas as Binary Search can be implemented only when the items are in sorted order and average-case time complexity is O(logn) and both Transversal have best-case Time complexity is O(1).
3 min read
Java Program to Search User Defined Object From a List By Using Binary Search Using Comparator
The Comparator interface in Java can be used to compare user-defined objects. The Comparator interface is present in java.util package. Binary search is a searching algorithm that uses the divide and conquers rule to search the presence of an element in a list or array. The binary search algorithm works only on a sorted list. In case the list is no
6 min read
Interpolation search vs Binary search
Interpolation search works better than Binary Search for a Sorted and Uniformly Distributed array. Binary Search goes to the middle element to check irrespective of search-key. On the other hand, Interpolation Search may go to different locations according to search-key. If the value of the search-key is close to the last element, Interpolation Sea
7 min read
Linear Search vs Binary Search
Prerequisite: Linear SearchBinary SearchLINEAR SEARCH Assume that item is in an array in random order and we have to find an item. Then the only way to search for a target item is, to begin with, the first position and compare it to the target. If the item is at the same, we will return the position of the current item. Otherwise, we will move to t
11 min read
Is there any search faster than Binary Search?
No, there is no search faster than Binary Search. Binary Search is the fastest searching algorithm for sorted data. It takes O(log2N) time to search any element in the sorted search space. In this article, we will discuss about how Binary Search works, it time complexity, comparison with other search algorithms, etc. How Does Binary Search Work?Bin
3 min read
Is exponential search faster than binary search?
Exponential search and binary search are two algorithms used to find a target element in a sorted array. While both algorithms have their advantages and disadvantages, exponential search is generally not considered to be faster than binary search. Time Complexity of Exponential Search:The time complexity of exponential search is O(log n), where n i
2 min read
Java Program for Anagram Substring Search (Or Search for all permutations)
Given a text txt[0..n-1] and a pattern pat[0..m-1], write a function search(char pat[], char txt[]) that prints all occurrences of pat[] and its permutations (or anagrams) in txt[]. You may assume that n > m. Expected time complexity is O(n) Examples: 1) Input: txt[] = "BACDGABCDA" pat[] = "ABCD" Output: Found at Index 0 Found at Index 5 Found a
4 min read
Java Program for Binary Search (Recursive and Iterative)
So as we all know binary search is one of the searching algorithms that is most frequently applied while dealing with data structures where the eccentric goal is not to traverse the whole array. Here array must be sorted as we check the middle element and ignore the half of the array which is of no use as per the number system. We basically ignore
4 min read
Java Program to Perform Binary Search on ArrayList
The ArrayList class is a part of the collection framework and is present in java.util package. It provides us with resizable or dynamic arrays in java. It is quite slower than standard arrays but can be helpful in some programs where we need to come up with cleaner and shorter code and lots of manipulation of an array is needed. The most effective
6 min read
Binary Search on Java Vector
Vector is a legacy class in Java and is present from Java 1.2 version. It implements the List interface of the Collection framework and is found in java.util package. Vector is just like an array that can grow dynamically. Vectors are synchronized ie vectors are thread-safe. Vectors are mainly used where thread synchronization is of utmost importan
3 min read
Java Program to Find the Cube Root of a Given Number Using Binary Search
Given a non-negative number find the cube root of a number using the binary search approach. Examples : Input: x = 27 Output: 3 Explanation: The cube root of 16 is 4. Input: x = 120 Output: 4 Explanation: The cube root of 120 lies in between 4 and 5 so floor of the cube root is 4.Naive Approach: Check the cube of every element till n and store the
2 min read
Java program to Find the Square Root of a Number using Binary Search
Given a non-negative number find the square root of a number using the binary search approach. Examples : Input: x = 16 Output: 4 Explanation: The square root of 16 is 4. Input: x = 5 Output: 2 Explanation: The square root of 5 lies in between 2 and 3 so floor of the square root is 2. Naive Approach: Check the square of every element till n and sto
3 min read
Binary Search vs contains Performance in Java List
Java provides two methods namely Collections.binarySearch() and contains() to find an element inside a list. Underneath the hood, contains() method uses indexOf() method to search for the element. indexOf() method linearly loops through the List and compares every element with the key until the key is found and returns true otherwise it returns fal
6 min read
Java Program to Construct a Binary Search Tree
Binary Search Tree (BST) is the widely used data structure in computer science, primarily known for the efficient search, insertion, and deletion operations. It is the type of binary tree where each node has at most two children, referred to as the left child and the right child. Binary Search Tree offers the efficient average-case time complexity
6 min read
Repeatedly search an element by doubling it after every successful search
Given an array "a[]" and integer "b". Find whether b is present in a[] or not. If present, then double the value of b and search again. We repeat these steps until b is not found. Finally we return value of b. Examples: Input : a[] = {1, 2, 3} b = 1 Output :4 Initially we start with b = 1. Since it is present in array, it becomes 2. Now 2 is also p
6 min read
Unbounded Binary Search Example (Find the point where a monotonically increasing function becomes positive first time)
Given a function 'int f(unsigned int x)' which takes a non-negative integer 'x' as input and returns an integer as output. The function is monotonically increasing with respect to the value of x, i.e., the value of f(x+1) is greater than f(x) for every input x. Find the value 'n' where f() becomes positive for the first time. Since f() is monotonic
11 min read
Binary Search in PHP
Binary Search is a searching technique used to search an element in a sorted array. In this article, we will learn about how to implement Binary Search in PHP using iterative and recursive way. Given a array of numbers, we need to search for the presence of element x in the array using Binary Search. Examples: Input : 1 2 3 4 5 5 Output : 5 Exists
3 min read
Minimum swaps so that binary search can be applied
Given an unsorted array of length n and an integer k, find the minimum swaps to get the position of k before using the binary search. Here we can swap any two numbers as many times as we want. If we cannot get the position by swapping elements, print "-1".Examples: Input : arr = {3, 10, 6, 7, 2, 5, 4} k = 4 Output : 2 Explanation : Here, after swap
14 min read
Calculating n-th real root using binary search
Given two number x and n, find n-th root of x. Examples: Input : 5 2Output : 2.2360679768025875 Input : x = 5, n = 3Output : 1.70997594668 In order to calculate nth root of a number, we can use the following procedure. If x lies in the range [0, 1) then we set the lower limit low = x and upper limit high = 1, because for this range of numbers the n
6 min read
Variants of Binary Search
Binary search is very easy right? Well, binary search can become complex when element duplication occurs in the sorted list of values. It's not always the "contains or not" we search using Binary Search, but there are 5 variants such as below:1) Contains (True or False) 2) Index of first occurrence of a key 3) Index of last occurrence of a key 4) I
15+ min read
What is Binary Search Algorithm?
Binary Search is a searching algorithm used in a sorted array by repeatedly dividing the search interval in half and the correct interval to find is decided based on the searched value and the mid value of the interval. Properties of Binary Search:Binary search is performed on the sorted data structure for example sorted array. Searching is done by
1 min read
Uniform Binary Search
Uniform Binary Search is an optimization of Binary Search algorithm when many searches are made on same array or many arrays of same size. In normal binary search, we do arithmetic operations to find the mid points. Here we precompute mid points and fills them in lookup table. The array look-up generally works faster than arithmetic done (addition
7 min read
Create a Sorted Array Using Binary Search
Given an array, the task is to create a new sorted array in ascending order from the elements of the given array.Examples: Input : arr[] = {2, 5, 4, 9, 8} Output : 2 4 5 8 9 Input : arr[] = {10, 45, 98, 35, 45} Output : 10 35 45 45 98 The above problem can be solved efficiently using Binary Search. We create a new array and insert the first element
9 min read
Check if an array is sorted and rotated using Binary Search
Pre-requisite: Check if an array is sorted and rotated using Linear SearchGiven an array arr[] of N distinct integers, the task is to check if this array is sorted when rotated counter-clockwise. A sorted array is not considered sorted and rotated, i.e., there should at least one rotation. Examples: Input: arr[] = { 3, 4, 5, 1, 2 } Output: true Exp
11 min read
Longest substring consisting of vowels using Binary Search
Given string str of length N, the task is to find the longest substring which contains only vowels using the Binary Search technique.Examples: Input: str = "baeicba" Output: 3 Explanation: Longest substring which contains vowels only is "aei".Input: str = "aeiou" Output: 5 Approach: Refer to the Longest substring of vowels for an approach in O(N) c
8 min read
Abstraction of Binary Search
What is the binary search algorithm? Binary Search Algorithm is used to find a certain value of x for which a certain defined function f(x) needs to be maximized or minimized. It is frequently used to search an element in a sorted sequence by repeatedly dividing the search interval into halves. Begin with an interval covering the whole sequence, if
7 min read
Binary Search Visualization using Pygame in Python
An algorithm like Binary Search can be understood easily by visualizing. In this article, a program that visualizes the Binary Search Algorithm has been implemented. The Graphical User Interface(GUI) is implemented in Python using pygame library. Approach Generate random array, sort it using any sorting algorithm, and fill the pygame window with ba
4 min read
Find H-Index for sorted citations using Binary Search
Given an array citations[] consisting of N integers in non-increasing order, representing citations, the task is to find the H-index. H-Index is usually assigned to the researcher denoting the contributions made in terms of no of papers and citations. H-index(H) is the largest value such that the researcher has at least H papers cited at least H ti
6 min read
Rearrange Array to find K using Binary Search algorithm without sorting
Given an array, arr[] of N distinct integers and an integer K, the task is to rearrange the given array in such a way, that K can be found with the help of Binary Search Algorithm in the rearranged array. Please note, the array is not to be sorted. Examples: Input: arr[] = {10, 7, 2, 5, 3, 8}, K = 7Output: 3 7 8 5 2 10 Explanation: Finding K in out
14 min read
Count of array elements that can be found using Randomized Binary Search on every array element
Given an array arr[] of size N, the task is to find the minimum count of array elements found by applying the Randomized Binary Search for each array elements. Examples: Input: arr[] = { 5, 4, 9 } Output: 2 Explanation: Applying Randomized Binary Search for arr[0] in the array. Initially, search space is [0, 2] Suppose pivot = 1 and arr[pivot] <
7 min read
three90RightbarBannerImg