Java Collection How to - Binary Search on Array








Question

We would like to know how to binary Search on Array.

Answer

//from  w  w w.j a  v  a 2  s  .c om
import java.util.Arrays;

public class Main {
  public static void main(String[] args) {
    byte bArray[] = { 1, 2, 4, 5 };
    Arrays.sort(bArray);

    byte searchValue = 2;

    int intResult = Arrays.binarySearch(bArray, searchValue);
    System.out.println("Result of binary search of 2 is : " + intResult);

    searchValue = 7;
    intResult = Arrays.binarySearch(bArray, searchValue);
    System.out.println("Result of binary search of 3 is : " + intResult);
  }
}

The code above generates the following result.