Binary Search — runnable Java
JavaUpdated
Runnable Java file — no imports, no Maven needed. Save it and run java binarysearch.java.
import java.util.Scanner;
public class binarysearch {
// Function to perform binary search on a sorted array
public static int binarySearch(int[] arr, int key) {
int left = 0, right = arr.length - 1;
while (left <= right) {
int mid = left + (right - left) / 2;
if (arr[mid] == key)
return mid; // Key found at index mid
else if (arr[mid] < key)
left = mid + 1;
else
right = mid - 1;
}
return -1; // Key not found
}
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
// Input: size of the array
System.out.print("Enter the number of elements in the array: ");
int n = sc.nextInt();
int[] arr = new int[n];
System.out.println("Enter " + n + " sorted integers:");
for (int i = 0; i < n; i++) {
arr[i] = sc.nextInt();
}
System.out.print("Enter the number to search: ");
int key = sc.nextInt();
int result = binarySearch(arr, key);
if (result == -1)
System.out.println("Element not found in the array.");
else
System.out.println("Element found at index: " + result);
sc.close();
}
}