Java Program to implement Binary Search on double array


Binary search on a double array can be implemented by using the method

java.util.Arrays.binarySearch(). This method returns the index of the required double 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) {
      double d_arr[] = { 5.2, 7.5, 9.7, 1.8, 4.0 };
      Arrays.sort(d_arr);
      System.out.print("The sorted array is: ");
      for (double i : d_arr) {
         System.out.print(i + " ");
      }
      System.out.println();
      int index1 = Arrays.binarySearch(d_arr, 9.7);
      System.out.println("The double value 9.7 is at index " + index1);
      int index2 = Arrays.binarySearch(d_arr, 2.5);
      System.out.println("The double value 2.5 is at index " + index2);
   }
}

Output

The sorted array is: 1.8 4.0 5.2 7.5 9.7
The double value 9.7 is at index 4
The double value 2.5 is at index -2

Now let us understand the above program.

The double array d_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 −

double d_arr[] = { 5.2, 7.5, 9.7, 1.8, 4.0 };
Arrays.sort(d_arr);
System.out.print("The sorted array is: ");
for (double i : d_arr) {
   System.out.print(i + " ");
}
System.out.println();

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

Updated on: 25-Jun-2020

204 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements