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}
Topic: Binary search on a sorted array
Answer
import java.util.Scanner;
class BinarySearch { public static void main(String args[]) { Scanner sc = new Scanner(System.in); int arr[] = {31, 36, 45, 50, 60, 75, 86, 90};
System.out.print("Enter the value to search : "); int key = sc.nextInt();
int lb = 0, ub = arr.length - 1, mid, pos = -1;
while(lb <= ub) { mid = (lb + ub) / 2; if(arr[mid] == key) { pos = mid; break; } else if(arr[mid] < key) lb = mid + 1; else ub = mid - 1; }
if(pos == -1) System.out.println("Search Unsuccessful"); else System.out.println("Search Successful"); System.out.println("Element found : " + arr[pos]); } }
The standard binary search template. Note the array is given already sorted — binary search requires it, and if a question gives unsorted data you must sort it first.
The idea is to halve the range at every step: look at the middle element if it matches the key, stop if it is smaller than the key, discard the left half (lb = mid + 1) if it is larger, discard the right half (ub = mid - 1) The loop continues while lb <= ub; when the bounds cross, the value is absent.
Three marks-carrying details: ub starts at arr.length - 1; pos is initialised to -1 so "not found" is distinguishable from "found at index 0"; and break stops the search as soon as a match is found.
Dry-run for 75: lb=0, ub=7, mid=3 (50 < 75) so lb=4; mid=5 (75 matches) — found in two comparisons where a linear search would have taken six.
arr[] int[8] - the sorted list of integers key int - the value entered by the user lb int - lower bound of the current search range ub int - upper bound of the current search range mid int - middle index of the current search range pos int - index where the key is found, or -1 if absent sc Scanner - object used to read input