import java.util.Scanner;
public class BinarySearch {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter the number of elements in the array: ");
int n = scanner.nextInt();
int[] arr = new int[n];
System.out.println("Enter the sorted elements:");
for (int i = 0; i < n; i++) {
arr[i] = scanner.nextInt();
}
System.out.print("Enter the element to search: ");
int key = scanner.nextInt();
scanner.close();
int result = binarySearch(arr, key);
if (result == -1)
System.out.println("Element not present in the array.");
else
System.out.println("Element found at index: " + result);
}
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;
if (arr[mid] < key)
left = mid + 1;
else
right = mid - 1;
}
return -1;
}
}
No comments:
Post a Comment