Skip to content
Related Articles

Related Articles

Arrays.binarySearch() in Java with examples | Set 2 (Search in subarray)
  • Difficulty Level : Easy
  • Last Updated : 30 Mar, 2021

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 index of the first element (inclusive) to be searched

toIndex – the index of the last element (exclusive) to be searched

 key  – the value to be searched for 

  • It is a static inbuilt method defined in Arrays (java.util.Arrays) class in java and returns the index of the specified key is found within the specified range.
  • Here, data_type can be any of the primitive data_type: byte, char, double, int, float, short, long and Object as well.
  • The above function Searches a range of the specified array of the given data type for the specified key using a binary search algorithm.
  • The range within which the specified key to be searched must be sorted (as by the Arrays.sort() method) prior to making this call. Otherwise, the result would be undefined. If the specified array contains multiple values same as the specified key, there is no guarantee which one will be found.

Returns : 
Index of the specified key is found within the specified range in the specified array, Otherwise (-(insertion point) – 1). 

The insertion point is defined as a point at which the specified key would be inserted: the index of the first element in the range greater than the key, or toIndex if all elements in the range are less than the specified key. 
Note: This guarantees that the return value will be >= 0 if and only if the key is found.

Examples:  

   byteArr[] = {10,20,15,22,35}

   key = 22 to be searched between the range 2 to 4 in specified array.



   Output: 3

   charArr[] = {‘g’,’p’,’q’,’c’,’i’}

   key = p to be searched between the range 1 to 4 in specified array.

   Output: 3

   intArr[] = {1,2,3,4,5,6}

   key = 3 to be searched between the range 1 to 4 in specified array.

   Output: 2

   doubleArr[] = {10.2,1.51,2.2,3.5}

   key = 1.5 to be searched between the range 1 to 4 in specified array.

   Output: -2 as it is the insertion point of 1.5

   floatArr[] = {10.2f,15.1f,2.2f,3.5f}

   key = 35.0 to be searched between the range 1 to 4 in specified array.

   Output: -5

  shortArr[] = {10,20,15,22,35}

  key = 5 to be searched between the range 0 to 4 in specified array.

  Output: -1

Implementation :
 

Java




// Java program to demonstrate working of  binarySearch()
// method for specified range in a sorted array.
import java.util.Arrays;
 
public class GFG {
    public static void main(String[] args)
    {
        byte byteArr[] = { 10, 20, 15, 22, 35 };
        char charArr[] = { 'g', 'p', 'q', 'c', 'i' };
        int intArr[] = { 1, 2, 3, 4, 5, 6 };
        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 };
 
        Arrays.sort(byteArr);
        Arrays.sort(charArr);
        Arrays.sort(intArr);
        Arrays.sort(doubleArr);
        Arrays.sort(floatArr);
        Arrays.sort(shortArr);
 
        byte byteKey = 22;
        char charKey = 'p';
        int intKey = 3;
        double doubleKey = 1.5;
        float floatKey = 35;
        short shortKey = 5;
 
        System.out.println(
            byteKey + " found at index = "
            + Arrays.binarySearch(byteArr, 2, 4, byteKey));
        System.out.println(
            charKey + " found at index = "
            + Arrays.binarySearch(charArr, 1, 4, charKey));
        System.out.println(
            intKey + " found at index = "
            + Arrays.binarySearch(intArr, 1, 4, intKey));
        System.out.println(doubleKey + " found at index = "
                           + Arrays.binarySearch(
                               doubleArr, 1, 4, doubleKey));
        System.out.println(floatKey + " found at index = "
                           + Arrays.binarySearch(
                               floatArr, 1, 4, floatKey));
        System.out.println(shortKey + " found at index = "
                           + Arrays.binarySearch(
                               shortArr, 0, 4, shortKey));
    }
}
Output
22 found at index = 3
p found at index = 3
3 found at index = 2
1.5 found at index = -2
35.0 found at index = -5
5 found at index = -1

Exceptions :  

  1. IllegalArgumentException : throws when starting index(fromIndex) is greater than the end index(toIndex) of specified range.(means: fromIndex > toIndex)
  2. ArrayIndexOutOfBoundsException : throws if one or both index are not valid means fromIndex<0 or toIndex > arr.length.

Important Points:  

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

Reference : 

https://docs.oracle.com/javase/7/docs/api/java/util/Arrays.html#binarySearch(int[],%20int)

This article is contributed by Nitsdheerendra. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@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.

Attention reader! Don’t stop learning now. Get hold of all the important Java Foundation and Collections concepts with the Fundamentals of Java and Java Collections Course at a student-friendly price and become industry ready. To complete your preparation from learning a language to DS Algo and many more,  please refer Complete Interview Preparation Course.

My Personal Notes arrow_drop_up
Recommended Articles
Page :