C Programs Tutorials | IT Developer
IT Developer

Java Programs



Share with a Friend

Binary Search Program - Java Programs

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’

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.nextLine().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

 
OUTPUT 1:
Character to be searched: A
Search is successful

OUTPUT 2:
Character to be searched: I
Search is not successful