How to Perform Binary Search on Int Array in Java


In this example, we’ll learn how to perform binary search for an element of int array with Arrays class in Java.

Source Code

package com.beginner.examples;

import java.util.Arrays;

public class BinarySearchIntArray {

	public static void main(String[] args) {
		
		//create int array.
		int intArray[] = {1,2,3,4,5};
		
		/*
		 * Please note that the int array MUST BE SORTED before it can be searched
		 * using binarySearch method.
		 */
		//sort byte array using Arrays.sort method
		Arrays.sort(intArray);
		int searchValue = 3;
		int result = Arrays.binarySearch(intArray,searchValue);
		System.out.println("Result of binary search of 3 is : " + result);

	}

}

Output:

Result of binary search of 3 is : 2

References

Imported packages in Java documentation:

Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments