Performing Binary Search on Java float Array - Java Language Basics

Java examples for Language Basics:float

Introduction

To perform binary search on float array use int binarySearch(float[] b, float value) of Arrays class.

The float array MUST BE SORTED before it can be searched using binarySearch method.

binarySearch method returns the index of the value to be searched, if found in the array.

If not found it returns (- (X) - 1) where X is the index where the the search value would be inserted.

Demo Code

 
import java.util.Arrays;

public class Main {

  public static void main(String[] args) {
    float floatArray[] = { 1.2f, 1.10f, 1.4f, 1.3f };

    Arrays.sort(floatArray);/*w  ww  .j  av  a  2 s. c  o m*/

    float searchValue = 41.74f;

    int intResult = Arrays.binarySearch(floatArray, searchValue);
    System.out.println("Result of binary search of 4.74 is : " + intResult);

    searchValue = 3.33f;
    intResult = Arrays.binarySearch(floatArray, searchValue);
    System.out.println("Result of binary search of 3.33 is : " + intResult);

  }
}

Result


Related Tutorials