Skip to content
Related Articles

Related Articles

Arrays.binarySearch() in Java with examples | Set 1

View Discussion
Improve Article
Save Article
  • Difficulty Level : Easy
  • Last Updated : 18 Apr, 2022
View Discussion
Improve Article
Save Article

Arrays.binarySearch() method searches the specified array of the given data type for the specified value using the binary search algorithm. The array must be sorted as by the Arrays.sort() method prior to making this call. If it is not sorted, the results are undefined. If the array contains multiple elements with the specified value, there is no guarantee which one will be found. Let us glide through the illustration provided below as follows.

Illustration:

Searching for 35 in byteArr[] = {10,20,15,22,35}
will give result as 4 as it is the index of 35

Searching for g in charArr[] = {'g','p','q','c','i'}
will give result as 0 as it is the index of 'g'

Searching for 22 in intArr[] = {10,20,15,22,35};
will give result as 3 as it is the index of 22

Searching for 1.5 in doubleArr[] = {10.2,15.1,2.2,3.5}
will give result as -1 as it is the insertion point of 1.5

Searching for 35.0 in floatArr[] = {10.2f,15.1f,2.2f,3.5f}
will give result as -5 as it is the insertion point of 35.0

Searching for 5 in shortArr[] = {10,20,15,22,35}
will give result as -1 as it is the insertion point of 5

It is the simplest and most efficient method to find an element in a sorted array in Java

Syntax:

public static int binarySearch(data_type arr, data_type key)

Remember: Here datatype can be any of the primitive data types such as byte, char, double, int, float, short, long, and even object as well.

Parameters: 

  • The array to be searched
  • The value to be searched for

Return Type: 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.

There are certain important points to be kept in mind as follows:

  • If the input list is not sorted, the results are undefined.
  • If there are duplicates, there is no guarantee which one will be found.

As above we already have discussed that we can operate this algorithm either Arrays.binarysearch() vs Collections.binarysearch(). Arrays.binarysearch() works for arrays which can be of primitive data type also. Collections.binarysearch() works for objects Collections like ArrayList and LinkedList

Example 1:

Java




// Java program to demonstrate working of Arrays.
// binarySearch() in a sorted array
 
// Importing Arrays class from
// java.util package
import java.util.Arrays;
 
// Main class
public class GFG {
 
    // Main driver method
    public static void main(String[] args)
    {
        // Declaring and initializing byte arrays
        // to search over them
        byte byteArr[] = { 10, 20, 15, 22, 35 };
        char charArr[] = { 'g', 'p', 'q', 'c', 'i' };
        int intArr[] = { 10, 20, 15, 22, 35 };
        double doubleArr[] = { 10.2, 15.1, 2.2, 3.5 };
        float floatArr[] = { 10.2f, 15.1f, 2.2f, 3.5f };
        short shortArr[] = { 10, 20, 15, 22, 35 };
 
        // Using sort() method of Arrays class
        // and passing arrays to be sorted as in arguments
        Arrays.sort(byteArr);
        Arrays.sort(charArr);
        Arrays.sort(intArr);
        Arrays.sort(doubleArr);
        Arrays.sort(floatArr);
        Arrays.sort(shortArr);
 
        // Primitive datatypes
        byte byteKey = 35;
        char charKey = 'g';
        int intKey = 22;
        double doubleKey = 1.5;
        float floatKey = 35;
        short shortKey = 5;
 
        // Now in sorted array we will fetch and
        // return elements/indiciesaccessing indexes to show
        // array is really sorted
 
        // Print commands where we are implementing
        System.out.println(
            byteKey + " found at index = "
            + Arrays.binarySearch(byteArr, byteKey));
        System.out.println(
            charKey + " found at index = "
            + Arrays.binarySearch(charArr, charKey));
        System.out.println(
            intKey + " found at index = "
            + Arrays.binarySearch(intArr, intKey));
        System.out.println(
            doubleKey + " found at index = "
            + Arrays.binarySearch(doubleArr, doubleKey));
        System.out.println(
            floatKey + " found at index = "
            + Arrays.binarySearch(floatArr, floatKey));
        System.out.println(
            shortKey + " found at index = "
            + Arrays.binarySearch(shortArr, shortKey));
    }
}


Output

35 found at index = 4
g found at index = 1
22 found at index = 3
1.5 found at index = -1
35.0 found at index = -5
5 found at index = -1

There are variants of this method in which we can also specify the range of array to search in. We will be discussing that as well as searching in an Object array in further posts.

Example 2:

Java




// Java Program to Illustrate 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 empty List
        List<Integer> al = new ArrayList<Integer>();
 
        // Adding elements to the List
        al.add(12);
        al.add(53);
        al.add(23);
        al.add(46);
        al.add(54);
 
        // Using binarySearch() method of Collections class
        // over random inserted element and storing the
        // index
        int index = Collections.binarySearch(al, 23);
 
        // Print and display the index
        System.out.print(index);
    }
}


Output

2

This article is contributed by Shikhar. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.


My Personal Notes arrow_drop_up
Recommended Articles
Page :

Start Your Coding Journey Now!