C Programs Tutorials | IT Developer
IT Developer

Java Programs



Share with a Friend

Binary Search Program - Java Programs

Define a class to search for a value input by the user from the list of values given below. If it is found display the message “Search successful”, otherwise display the message “Search element not found” using Binary search technique.


5.6, 11.5, 20.8, 35.4, 43.1, 52.4, 66.6, 78.9, 80.0, 95.5.

import java.util.Scanner; class Search{ public static void main(String args[]){ Scanner in = new Scanner(System.in); double a[] = {5.6, 11.5, 20.8, 35.4, 43.1, 52.4, 66.6, 78.9, 80.0, 95.5}; System.out.print("Element to be searched: "); double key = Double.parseDouble(in.nextLine()); 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 element not found"); else System.out.println("Search successful"); } }

Output

 
OUTPUT 1:
Element to be searched: 20.8
Search successful

OUTPUT 2:
Element to be searched: 20
Search element not found