Java Program to implement Binary Search on char array

Java 8Object Oriented ProgrammingProgramming

Binary search on a char array can be implemented by using the method java.util.Arrays.binarySearch(). This method returns the index of the required char element if it is available in the array, otherwise, it returns (-(insertion point) - 1) where the insertion point is the position at which the element would be inserted into the array.

A program that demonstrates this is given as follows −

Example

 Live Demo

import java.util.Arrays;
public class Demo {
   public static void main(String[] args) {
      char c_arr[] = { 'b', 's', 'l', 'e', 'm' };
      Arrays.sort(c_arr);
      System.out.print("The sorted array is: ");
      for (char i : c_arr) {
         System.out.print(i + " ");
      }
      System.out.println();
      int index1 = Arrays.binarySearch(c_arr, 'e');
      System.out.println("The character e is at index " + index1);
      int index2 = Arrays.binarySearch(c_arr, 'z');
      System.out.println("The character z is at index " + index2);
   }
}

Output

The sorted array is: b e l m s
The character e is at index 1
The character z is at index -6

Now let us understand the above program.

The char array c_arr[ ] is defined and then sorted using  Arrays.sort(). Then the sorted array is printed using for loop. A code snippet which demonstrates this is as follows −

char c_arr[] = { 'b', 's', 'l', 'e', 'm' };
Arrays.sort(c_arr);
System.out.print("The sorted array is: ");
for (char i : c_arr) {
   System.out.print(i + " ");
}
System.out.println();

The method Arrays.binarySearch() is used to find the index of element ‘e’ and ‘z’. Since ‘e’ is in the array, its index is displayed. Also, ‘z’ is not in the array and so the value according to (-(insertion point) - 1) is displayed. A code snippet which demonstrates this is as follows −

int index1 = Arrays.binarySearch(c_arr, 'e');
System.out.println("The character e is at index " + index1);
int index2 = Arrays.binarySearch(c_arr, 'z');
System.out.println("The character z is at index " + index2);
raja
Published on 08-Jan-2019 14:26:02
Advertisements