Open In App

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

Last Updated : 30 Mar, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

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

Complexity Analysis:

Time Complexity:
The time complexity of the Arrays.binarySearch() method is O(log n) where n is the length of the input array. This is because the method uses binary search algorithm to find the target element in the sorted array.

Auxiliary Space:
The auxiliary space used by the Arrays.binarySearch() method is O(1) as it does not require any extra space other than the input array to perform the search operation.

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

Complexity Analysis:

Time Complexity:
The time complexity of the binarySearch() method in the Collections class is O(log n) where n is the number of elements in the list.

Auxiliary Space:
The binarySearch() method in the Collections class does not require any extra space and thus has an auxiliary space complexity of O(1).



Previous Article
Next Article

Similar Reads

Arrays.binarySearch() in Java with examples | Set 2 (Search in subarray)
Arrays.binarySearch()| Set 1 Covers how to find an element in a sorted array in Java. This set will cover "How to Search a key in an array within a given range including only start index". Syntax : public static int binarySearch(data_type[] arr, int fromIndex, int toIndex, data_type key) Parameters : arr – the array to be searched fromIndex – the i
5 min read
Collections.binarySearch() in Java with Examples
java.util.Collections.binarySearch() method is a java.util.Collections class method that returns position of an object in a sorted list. // Returns index of key in sorted list sorted in // ascending order public static int binarySearch(List slist, T key) // Returns index of key in sorted list sorted in // order defined by Comparator c. public stati
4 min read
Java.util.Arrays.parallelSetAll(), Arrays.setAll() in Java
Prerequisites : Lambda Expression in Java 8IntUnaryOperator Interface parallelSetAll and setAll are introduced in Arrays class in java 8. parallelSetAll(): It set all the element in the specified array in parallel by the function which compute each element. Syntax: public static void parallelSetAll(double[] arr, IntToDoubleFunction g) Parameters :
5 min read
Java.util.Arrays.equals() in Java with Examples
Today we are going to discuss the simplest way to check whether two arrays are equal or not. Two arrays are considered equal if both arrays contain the same number of elements, and all corresponding pairs of elements in the two arrays are equal. In other words, two arrays are equal if they contain the same elements in the same order. Also, two arra
4 min read
Difference Between Arrays.toString() and Arrays.deepToString() in Java
The deepToString() method of the Arrays class returns the string representation of the deep contents of the specified Object array. Unlike Arrays. toString(), if the array contains other arrays as elements, the string representation includes their contents, and so on. Arrays.toString(): Returns a string representation of the contents of the specifi
3 min read
Java 8 | Arrays parallelSort() method with Examples
Java 8 introduced a new method called as parallelSort() in java.util.Arrays Class. It uses Parallel Sorting of array elements Algorithm of parallelSort() 1. The array is divided into sub-arrays and that sub-arrays is again divided into their sub-arrays, until the minimum level of detail in a set of array. 2. Arrays are sorted individually by multip
4 min read
Arrays asList() method in Java with Examples
The asList() method of java.util.Arrays class is used to return a fixed-size list backed by the specified array. This method acts as a bridge between array-based and collection-based APIs, in combination with Collection.toArray(). The returned list is serializable and implements RandomAccess. Tip: This runs in O(1) time. Syntax: public static List
3 min read
util.Arrays vs reflect.Array in Java with Examples
Array class in java.lang.reflect package is a part of the Java Reflection. This class provides static methods to create and access Java arrays dynamically. It is a final class, which means it can’t be instantiated or changed. Only the methods of this class can be used by the class name itself. On the other hand, Arrays class in java.util package is
2 min read
Java Arrays compare() Method with Examples
Arrays compare() method in Java comes under the Arrays class and java.util package. This method compares two arrays lexicographically (Dictionary order). There are two different versions of different overloads for Boolean, byte, char, double, float, int, long, short, and Object arrays. This method returns values as per the below-mentioned cases. It
4 min read
Arrays.sort() in Java with examples
Arrays class is a class containing static methods that are used with arrays in order to search, sort, compare, insert elements, or return a string representation of an array. So let us specify the functions first and later onwards we will be discussing the same. They are as follows being present in java.util.Arrays class. Here we will be discussing
7 min read