Java Collection Tutorial - Java Arrays.binarySearch(short[] a, int fromIndex, int toIndex, short key)








Syntax

Arrays.binarySearch(short[] a, int fromIndex, int toIndex, short key) has the following syntax.

public static int binarySearch(short[] a,  int fromIndex,  int toIndex,  short key)

Example

In the following code shows how to use Arrays.binarySearch(short[] a, int fromIndex, int toIndex, short key) method.

Binary search needs sorted arrays.

/*from   w  w w.  j a va2 s  . c  o  m*/
import java.util.Arrays;

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

    // initializing sorted short array
    short shortArr[] = {1,2,15,52,110};

    // value to search
    short searchVal = 15;

    // entering range of index
    int retVal = Arrays.binarySearch(shortArr,3,4,searchVal);

    System.out.println("The index of element 15 is : " + retVal);
  }
}

The code above generates the following result.