Define a class 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". 2, 5, 7, 10, 15, 20, 29, 30, 46, 50
Topic: Binary search on an integer array
Answer
import java.util.Scanner;
class BinarySearch { public static void main(String args[]) { Scanner sc = new Scanner(System.in); int arr[] = {2, 5, 7, 10, 15, 20, 29, 30, 46, 50};
System.out.print("Enter the element 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 element not found"); else System.out.println("Element " + key + " found at position " + (pos + 1)); } }
Binary search works only on SORTED data — check the given list and you will see it is already in ascending order, which is why the question can ask for this method.
The technique halves the search range each time: find the middle element if it matches, stop if it is smaller than the key, the key must lie to the right, so lb = mid + 1 otherwise the key lies to the left, so ub = mid - 1 The loop runs while lb <= ub; once the bounds cross, the element is absent.
Two details carry marks: ub starts at arr.length - 1 (not arr.length), and pos starts at -1 so that "not found" can be told apart from "found at index 0".
Dry-run for 29: lb=0, ub=9, mid=4 (15 < 29) so lb=5; mid=7 (30 > 29) so ub=6; mid=5 (20 < 29) so lb=6; mid=6 (29 matches) — found at index 6, position 7. Only four comparisons for ten elements, against up to ten for a linear search.
arr[] int[10] - the sorted list of integers key int - the element 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