Skip to Content

Performing Binary Search on Java float Array Example

  1. /*
  2.   Performing Binary Search on Java float Array Example
  3.   This java example shows how to perform binary search for an element of
  4.   java float array using Arrays class.
  5. */
  6.  
  7. import java.util.Arrays;
  8.  
  9. public class BinarySearchFloatArrayExample {
  10.  
  11.   public static void main(String[] args) {
  12.     //create float array
  13.     float floatArray[] = {1.23f,2.10f,4.74f,5.34f};
  14.    
  15.     /*
  16.       To perform binary search on float array use
  17.       int binarySearch(float[] b, float value) of Arrays class. This method searches
  18.       the float array for specified float value using binary search algorithm.
  19.      
  20.       Please note that the float array MUST BE SORTED before it can be searched
  21.       using binarySearch method.
  22.      
  23.       This method returns the index of the value to be searched, if found in the
  24.       array.
  25.       Otherwise it returns (- (X) - 1)
  26.       where X is the index where the the search value would be inserted.
  27.       i.e. index of first element that is grater than the search value
  28.       or array.length, if all elements of an array are less than the
  29.       search value.
  30.     */
  31.    
  32.     //sort float array using Arrays.sort method
  33.     Arrays.sort(floatArray);
  34.    
  35.     //value to search
  36.     float searchValue = 4.74f;
  37.    
  38.     //since 4.74 is present in float array, index of it would be returned
  39.     int intResult = Arrays.binarySearch(floatArray,searchValue);
  40.     System.out.println("Result of binary search of 4.74 is : " + intResult);
  41.    
  42.     //lets search something which is not in float array !
  43.     searchValue = 3.33f;
  44.     intResult = Arrays.binarySearch(floatArray,searchValue);
  45.     System.out.println("Result of binary search of 3.33 is : " + intResult);
  46.  
  47.   }
  48. }
  49.  
  50. /*
  51. Output would be
  52. Result of binary search of 4.74 is : 2
  53. Result of binary search of 3.33 is : -3
  54. */