Binary Search Implementation on Char Array in Java



In this article, we will learn to implement binary search on char array using Java. The binary search on a char array can be implemented by using the Arrays.binarySearch() method of java.util package. 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.

Problem Statement

Write a program in Java to implement binary search on char array

Input

'b', 's', 'l', 'e', 'm'

Output

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

Steps to implement binary search on char array

Following are the steps to implement binary search on char array ?

  • First define a character Array with unsorted elements we will be using Arrays.sort() to sort the character array.
  • Iterate through the array using for loop to display the sorted characters.
  • Call Arrays.binarySearch() method to search for specific characters in the sorted array.
  • Check the returned index if the character is found, it returns the index.
  • If the character is not found, it returns -1.

Java program to implement binary search on char array

Below is the Java program to implement binary search on char array ?

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

Code explanation 

The above program starts by creating a character array c_arr[] with unsorted elements like 'b', 's', 'l', 'e', and 'm'. It sorts this array using Arrays.sort() from the java.util package and then prints the sorted characters using a for loop. Next, it searches for the character 'e' using Arrays.binarySearch(), which finds it and shows its index. The program also looks for the character 'z', which isn't in the array, and the method returns a negative value, indicating where 'z' would fit in the sorted array. Overall, this program effectively demonstrates how to perform binary search on a character array in Java.

Updated on: 2024-09-29T02:49:49+05:30

1K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements