C Programs Tutorials | IT Developer
IT Developer

Java Programs



Share with a Friend

Binary Search Program - Java Programs

Write a program to perform binary search on a list of integers given below, to search for an element input by the user. If it is found, display the element along with its position, otherwise display the message “Search element not found”.
5, 7, 9, 11, 15, 20, 30, 45, 89, 97.

import java.util.Scanner; class Binary{ public static void main(String args[]){ Scanner in = new Scanner(System.in); int a[] = {5, 7, 9, 11, 15, 20, 30, 45, 89, 97}; System.out.print("Element to be searched: "); int s = Integer.parseInt(in.nextLine()); int low = 0; int high = a.length - 1; int mid = 0; while(low <= high){ mid = (low + high) / 2; if(s == a[mid]) break; else if(s < a[mid]) high = mid - 1; else low = mid + 1; } if(low > high) System.out.println("Search element not found"); else System.out.println("Found at position " + (mid + 1)); } }

Output

 
 OUTPUT 1: 
 Element to be searched: 15
Found at position 5

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