Computer Applications
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’
Answer
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");
}
}Output
Related Questions
Define a class to accept values into a 4 × 4 integer array. Calculate and print the NORM of the array.
NORM is the square root of sum of squares of all elements.1 2 1 3 5 2 1 6 3 6 1 2 3 4 6 3Sum of squares of elements = 1 + 4 + 1 + 9 + 25 + 4 + 1 + 36 + 9 + 36 + 1 + 4 + 9 + 16 + 36 + 9 = 201
NORM = Square root of 201 = 14.177446878757825Define a class to accept a String and print if it is a Super String or not. A String is Super if the number of uppercase letters are equal to the number of lowercase letters. [Use Character and String methods only]
Example: “COmmITmeNt”
Number of uppercase letters = 5
Number of lowercase letters = 5
String is a Super StringDefine a class to overload the method print() as follows:
void print() – To print the given format using nested loops.@#@#@ @#@#@ @#@#@ @#@#@double print(double a, double b) – To display the sum of numbers between a and b with difference of 0.5.
e.g. if a = 1.0, b = 4.0
Output is: 1.0 + 1.5 + 2.0 + 2.5 + … + 4.0
int print(char ch1, char ch2) – Compare the two characters and return the ASCII code of the largest character.Define a class to accept a number. Check if the sum of the largest digit and the smallest digit is an even number or an odd number. Print appropriate messages.
Sample Input: 6425 3748 Largest digit: 6 8 Smallest digit: 2 3 Sample Output: Sum is even Sum is odd