Java Program to implement Binary Search on an array

Java 8Object Oriented ProgrammingProgramming

Binary search can be implemented on an array by using the method java.util.Arrays.binarySearch(). This method returns the index of the required element if it is available in the array, otherwise it returns (- (insertion point) - 1) where the insertion point is the position at which the element would be inserted into the array.

A program that demonstrates this is given as follows −

Example

 Live Demo

import java.util.Arrays;
public class Demo {
   public static void main(String[] args) {
      int arr[] = { 3, 9, 1, 6, 4};
      Arrays.sort(arr);
      System.out.print("The sorted array is: ");
      for (int i : arr) {
         System.out.print(i + " ");
      }
      System.out.println();
      int index1 = Arrays.binarySearch(arr, 6);
      System.out.println("The integer 6 is at index " + index1);
      int index2 = Arrays.binarySearch(arr, 7);
      System.out.println("The integer 7 is at index " + index2);
   }
}

Output

The sorted array is: 1 3 4 6 9
The integer 6 is at index 3
The integer 7 is at index -5

Now let us understand the above program.

The int array arr[] is defined and then sorted using Arrays.sort(). Then the sorted array is printed using for loop. A code snippet which demonstrates this is as follows −

int arr[] = { 3, 9, 1, 6, 4};
Arrays.sort(arr);
System.out.print("The sorted array is: ");
for (int i : arr) {
   System.out.print(i + " ");
}
System.out.println();

The method Arrays.binarySearch() is used to find the index of element 6 and 7. Since 6 is in the array, its index is displayed. Also, 7 is not in the array and so the value according to (-(insertion point) - 1) is displayed. A code snippet which demonstrates this is as follows −

int index1 = Arrays.binarySearch(arr, 6);
System.out.println("The integer 6 is at index " + index1);
int index2 = Arrays.binarySearch(arr, 7);
System.out.println("The integer 7 is at index " + index2);
raja
Published on 09-Jan-2019 14:51:25
Advertisements