How to perform binary search on an array in java?

Java 8Object Oriented ProgrammingProgramming

The Arrays class of java package provides you a method named binarySearch() using this method you can perform a binary search on an array in Java.

Example

Live Demo

import java.util.Arrays;

public class ArrayDemo {
   public static void main(String[] args) {
      int intArr[] = {30,20,5,12,55};
      Arrays.sort(intArr);
      System.out.println("The sorted int array is:");
      for (int number : intArr) {
         System.out.println("Number = " + number);
      }
      int searchVal = 12;
      int retVal = Arrays.binarySearch(intArr,searchVal);
      System.out.println("The index of element 12 is : " + retVal);
   }
}

Output

The sorted int array is:
Number = 5
Number = 12
Number = 20
Number = 30
Number = 55
The index of element 12 is: 1
raja
Published on 09-Jan-2018 17:57:53
Advertisements