Tutorialspoint.dev

Binary Search in Java

There are two ways to do binary search in Java.

  1. Arrays.binarysearch() works for arrays which can be of primitive data type also.
    // Java program to demonstrate working of Arrays.
    // binarySearch() in a sorted array.
    import java.util.Arrays;
      
    public class GFG {
        public static void main(String[] args)
        {
            int arr[] = { 10, 20, 15, 22, 35 };
            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
    
  2. Collections.binarysearch() works for objects Collections like ArrayList and LinkedList.
    // Java program to demonstrate working of Collections.
    // binarySearch()
    import java.util.List;
    import java.util.ArrayList;
    import java.util.Collections;
       
    public class GFG
    {
        public static void main(String[] args)
        {
            List<Integer> al = new ArrayList<Integer>();
            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
    

What if input is not sorted?
If input list is not sorted, the results are undefined.

What if there are duplicates?
If there are duplicates, there is no guarantee which one will be found.



How does Collections.binarySearch work for LinkedList?
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.

What is significant value of 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.

How to implement our own Binary search in 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

Is there any function like lower_bound() or upper_bound() in C++ STL?
There are no such functions in Java till Java 9.



This article is attributed to GeeksforGeeks.org

leave a comment

code

0 Comments

load comments

Subscribe to Our Newsletter