How to Perform Binary Search on Java Char Array


In this example, we will write an example to perform binary search for an element of char array using Arrays class in Java.

Source Code

package com.beginner.examples;

import java.util.Arrays;

public class BinarySearchCharArray {

	public static void main(String[] args) {
		
		//create char array.
		char charArray[] = {'A','B','C','D'};
		
		/*
		 * Please note that the char array MUST BE SORTED before it can be searched
		 * using binarySearch method.
		 */
		Arrays.sort(charArray);
		int result = Arrays.binarySearch(charArray, 'C');
		System.out.println("Result of binary search of C is : " + result);

	}

}

Output:

Result of binary search of C is : 2

References

Imported packages in Java documentation:

Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments