OneCompiler

BINARY SEARCH :search for a character input by the user

154

*** Define a class to accept 20 characters in an array and search for a character input by the user and display the message “Search Successful” if the character is found in the array, otherwise
display the message “Search unsuccessful” using Binary search technique.***

import java.util.;
class Array_P3
{
public static void main(String[]args)
{
int flg=0; int lb=0, ub=19,M;
Scanner sc=new Scanner(System.in);
char arr[]=new char[20];/** stores 20 characters
/
System.out.println("Enter 20 characters");
for(int i=0;i<20;i++)
{
arr[i]=sc.next().charAt(0);
}
System.out.println("Enter a char to search");
char search=sc.next().charAt(0);
while(lb<=ub)
{
M=(lb+ub)/2;
if(search>arr[M])
lb=M+1;
else if(search<arr[M])
ub=M-1;
else if (search==arr[M])
{
flg = 1;
System.out.println("Search Successful");
break;
}
}
if(flg == 0)
System.out.println("Search Unsuccessful");
}
}

FOR CODE,
CLICK : https://onecompiler.com/java/3y4ehedk8 (TO FIND OUTPUT)