C Programs Tutorials | IT Developer
IT Developer

Java Programs



Share with a Friend

Binary Search Technique Program - Java Programs

Question 5
Write a program to search for an integer value input by the user in the sorted list given below using binary search technique. If found, display “Search Successful” and print the element, otherwise display “Search Unsuccessful”
{31, 36, 45, 50, 60, 75, 86, 90}

import java.util.Scanner; class BinarySearch{ public static void main(String[] args){ Scanner in = new Scanner(System.in); int a[] = {31, 36, 45, 50, 60, 75, 86, 90}; System.out.print("Element to be searched: "); int key = Integer.parseInt(in.nextLine()); int low = 0; int high = a.length - 1; int mid; 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 Unsuccessful"); else System.out.println("Search Successful: " + key); } }

Output

 
 OUTPUT 1: 
Element to be searched: 50
Search Successful: 50 

 OUTPUT 2: 
Element to be searched: 51
Search Unsuccessful