How to Perform Binary Search on Long Array in Java


In this example we will show how to perform binary search for an element of java long array with Arrays class.

Source Code

package com.beginner.examples;

import java.util.Arrays;

public class BinarySearchLongArray {

	public static void main(String[] args) {
		
		//create long array.
		long longArray[] = {1,2,3,4,5};
		
		/*
		 * Please note that the long array MUST BE SORTED before it can be searched
		 * using binarySearch method.
		 */
		//sort byte array using Arrays.sort method
		Arrays.sort(longArray);
		long searchValue = 3;
		int result = Arrays.binarySearch(longArray,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