How to Perform Binary Search on Float Array in Java


Here we will learn how to perform binary search for an element of java float array with Arrays class.

Source Code

package com.beginner.examples;

import java.util.Arrays;

public class BinarySearchFloatArray {

	public static void main(String[] args) {
		
		//create float array.
		float floatArray[] = {5.21f,3.14f,9.96f,5.32f};
		
		/*
		 * Please note that the float array MUST BE SORTED before it can be searched
		 * using binarySearch method.
		 */
		Arrays.sort(floatArray);
		int result = Arrays.binarySearch(floatArray,9.96f);
		System.out.println("Result of binary search of 9.96 is : " + result);

	}

}

Output:

Result of binary search of 9.96 is : 3

References

Imported packages in Java documentation:

Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments