Java Program to implement Binary Search on float array

Java 8Object Oriented ProgrammingProgramming

Binary search on a float array can be implemented by using the method java.util.Arrays.binarySearch(). This method returns the index of the required float 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) {
      float f_arr[] = { 5.2f, 9.5f, 6.5f, 2.8f, 3.6f };
      Arrays.sort(f_arr);
      System.out.print("The sorted array is: ");
      for (float i : f_arr) {
         System.out.print(i + " ");
      }
      System.out.println();
      int index1 = Arrays.binarySearch(f_arr, 6.5f);
      System.out.println("The float value 6.5 is at index " + index1);
      int index2 = Arrays.binarySearch(f_arr, 7.5f);
      System.out.println("The float value 7.5 is at index " + index2);
   }
}

Output

The sorted array is: 2.8 3.6 5.2 6.5 9.5 The float value 6.5 is at index 3 The float value 7.5 is at index -5

Now let us understand the above program.

The float array f_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 −

float f_arr[] = { 5.2f, 9.5f, 6.5f, 2.8f, 3.6f };
Arrays.sort(f_arr);
System.out.print("The sorted array is: ");
for (float i : f_arr) {
   System.out.print(i + " ");
}
System.out.println();

The method Arrays.binarySearch() is used to find the index of element 6.5 and 7.5. Since 6.5 is in the array, its index is displayed. Also, 7.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(f_arr, 6.5f);
System.out.println("The float value 6.5 is at index " + index1);
int index2 = Arrays.binarySearch(f_arr, 7.5f);
System.out.println("The float value 7.5 is at index " + index2);
raja
Published on 09-Jan-2019 06:58:52
Advertisements