6
Define a class to initialize the following data in an array.
Search for a given character input by the user, using the Binary Search technique.
Print “Search successful” if the character is found otherwise print “Search is not successful”.
‘A’, ‘H’, ‘N’, ‘P’, ‘S’, ‘U’, ‘W’, ‘Y’, ‘Z’, ‘b’, ‘d’
Show SolutionHide Solution↓
import java.util.Scanner;
class Search{
public static void main(String[] args){
Scanner in = new Scanner(System.in);
char a[] = {'A', 'H', 'N', 'P', 'S', 'U', 'W', 'Y', 'Z', 'b', 'd'};
System.out.print("Character to be searched: ");
char key = in.next().charAt(0);
int low = 0;
int high = a.length - 1;
int mid = 0;
while(low <= high){
mid = (low + high) / 2;
if(key == a[mid])
break;
else if(key < a[mid])
high = mid - 1;
else
low = mid + 1;
}
if(low > high)
System.out.println("Search is not successful");
else
System.out.println("Search is successful");
}
}
