Pankaj Gupta Scholar
Program to perform Binary Search
Here’s a simple Java program to perform binary search on a sorted array of integers. Binary search works by repeatedly dividing the array in half and comparing the target value to the middle element, reducing the search interval by half each time.
import java.util.Scanner;
public class BinarySearch {
// Method to perform binary search
public static int binarySearch(int[] array, int target) {
int low = 0;
int high = array.length – 1;
// Continue searching while the range is valid
while (low <= high) {
// Calculate the middle index
int mid = low + (high – low) / 2;
// Check if the target is at the mid
if (array[mid] == target) {
return mid; // Target found, return the index
}
// If the target is greater, ignore the left half
if (array[mid] < target) {
low = mid + 1;
}
// If the target is smaller, ignore the right half
else {
high = mid – 1;
}
}
// Return -1 if the target is not found
return -1;
}
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
// Input: Sorted array
System.out.print(“Enter the number of elements in the array: “);
int n = scanner.nextInt();
int[] array = new int[n];
System.out.println(“Enter ” + n + ” sorted elements: “);
for (int i = 0; i < n; i++) {
array[i] = scanner.nextInt();
}
// Input: Target element to search
System.out.print(“Enter the element to search for: “);
int target = scanner.nextInt();
// Perform binary search
int result = binarySearch(array, target);
// Output the result
if (result == -1) {
System.out.println(“Element not found.”);
} else {
System.out.println(“Element found at index: ” + result);
}
scanner.close();
}
}
Explanation of the program
- Input: The user enters the number of elements, a sorted array, and the target element to search.
- Binary Search:
- The array is divided into two halves by calculating the middle element.
- If the target is equal to the middle element, the search is successful.
- If the target is smaller than the middle element, the search continues on the left half. Otherwise, it continues on the right half.
- This process repeats until the target is found or the search space is exhausted.
- Output: The program prints the index of the target element if found, or a message if it’s not found.