Java Program to implement Binary Search on long array


Binary search on a long array can be implemented by using the method java.util.Arrays.binarySearch(). This method returns the index of the required long 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) {
      long long_arr[] = { 250L, 500L, 175L, 90L, 415L };
      Arrays.sort(long_arr);
      System.out.print("The sorted array is: ");
      for (long i : long_arr) {
         System.out.print(i + " ");
      }
      System.out.println();
      int index1 = Arrays.binarySearch(long_arr, 415L);
      System.out.println("The long value 415 is at index " + index1);
      int index2 = Arrays.binarySearch(long_arr, 50L);
      System.out.println("The long value 50 is at index " + index2);
   }
}

Output

The sorted array is: 90 175 250 415 500
The long value 415 is at index 3
The long value 50 is at index -1

Now let us understand the above program.

The long array long_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 −

long long_arr[] = { 250L, 500L, 175L, 90L, 415L };
Arrays.sort(long_arr);
System.out.print("The sorted array is: ");
for (long i : long_arr) {
   System.out.print(i + " ");
}
System.out.println();

The method Arrays.binarySearch() is used to find the index of element 415 and 50. Since 415 is in the array, its index is displayed. Also, 50 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(long_arr, 415L);
System.out.println("The long value 415 is at index " + index1);
int index2 = Arrays.binarySearch(long_arr, 50L);
System.out.println("The long value 50 is at index " + index2);

Updated on: 25-Jun-2020

150 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements