Advertisements
Advertisements
प्रश्न
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’
कोड लेखन
Advertisements
उत्तर
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
क्या इस प्रश्न या उत्तर में कोई त्रुटि है?
