Arrays.binarySearch(char[], char): This method is available in java.util.Arrays class of Java.
Syntax:
int java.util.Arrays.binarySearch(char[] a, char key)
This method takes two arguments one of type char array and the other of type char as its parameters. This method searches the specified array of chars for the specified value.
Note: The array must be sorted.
Parameters: Two parameters are required for this method.
a: the array to be searched.
key: the value to be searched for.
Returns: index of the search key, if it is contained in the array; otherwise, (-(insertion point) - 1).
Note: The insertion point is defined as the point at which the key would be inserted into the array: the index of the first element greater than the key, or a.length if all elements in the array are less than the specified key.
Exceptions: NA
Approach
Java
import java.util.Arrays;public class ArraysbinarySearchchar {public static void main(String[] args) {// for char typechar charArray[] = { 'a', 'd', 'f', 'h', 'o' };char charKey = 'f';// to ensure array is sortedArrays.sort(charArray);System.out.println(Arrays.binarySearch(charArray,charKey));}}
Output:
2
No comments:
Post a Comment