Define a class to initialise 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'
Topic: Binary search on a character array
Answer
import java.util.Scanner;
class BinSearch { public static void main(String args[]) { Scanner sc = new Scanner(System.in); char arr[] = {'A','H','N','P','S','U','W','Y','Z','b','d'};
System.out.print("Enter the character to search : "); char key = sc.next().charAt(0);
int lb = 0, ub = arr.length - 1, mid, pos = -1;
while(lb <= ub) { mid = (lb + ub) / 2; if(arr[mid] == key) { pos = mid; break; } else if(arr[mid] < key) lb = mid + 1; else ub = mid - 1; }
if(pos == -1) System.out.println("Search is not Successful"); else System.out.println("Search Successful"); } }
Binary search is a guaranteed question type, so learn this template exactly. It works only on a SORTED array — note the given data is already in ascending order, and that 'b' and 'd' come after 'Z' because lowercase ASCII codes (97 onward) are higher than uppercase (65 to 90).
The method: keep a lower bound and an upper bound, look at the middle element, and throw away half the array each time. if arr[mid] equals the key - found, store the position and break if arr[mid] is less than key - the key must lie to the right, so lb = mid + 1 otherwise - the key must lie to the left, so ub = mid - 1 The loop continues while lb <= ub; when the bounds cross, the element is absent.
Dry-run for ‘d’ in this array of 11 elements: lb=0, ub=10, mid=5 ('U' < 'd') so lb=6; mid=8 ('Z' < 'd') so lb=9; mid=9 ('b' < 'd') so lb=10; mid=10 ('d' matches) - found.
Two frequent errors: using ub = arr.length instead of arr.length - 1, and forgetting that pos must start at -1 so you can tell "not found" from "found at index 0".
arr[] char[] - the sorted array of characters to be searched key char - the character entered by the user lb int - lower bound of the current search range ub int - upper bound of the current search range mid int - middle index of the current search range pos int - index where the key is found, or -1 if absent sc Scanner - object used to read input from the keyboard