English

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 - Computer Applications

Advertisements
Advertisements

Question

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’

Code Writing
Advertisements

Solution

import java.util.*;
public class BinSearch
{
int binSearch(char a[], int low, int high, int x)
{
while (low <= high) {
  int m = (low + high) /2;
  if (a[m]=x) {
     return m;
} else if (a[m]>x) {
     high = m- 1;
} else {
  low = m +1;
 }
}
return -1;
}
public static void main(String args[])
{
  BinSearch ob = new BinSearch();
  Scanner sc=new Scanner(System.in);
  char arr[]= {'A','H','N','P','S','U',W','Y',Z',b,'d'};
  int n = arr.length;
  char ch;
  System.out.println("Enter search character :");
  ch=sc.nextLine().charAt(0);
  int res = ob.binSearch(arr,0,n - 1,ch);
  if (res=-1)
     System.out.println("The Search is not
     successful");
else
     System.out.println(" The Search is
     successful....., Element found at index"+ res);
shaalaa.com
  Is there an error in this question or solution?
2024-2025 (March) Official Board
Share
Notifications

Englishहिंदीमराठी


      Forgot password?
Use app×