How to Perform Binary Search on Java Byte Array


Here we will learn how to perform binary search for an element of java byte array.

Source Code

package com.beginner.examples;

import java.util.Arrays;

public class BinarySearchByteArray {

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