public class BinarySearch {
public static void main(String[] args) {
int[] arr = {2, 4, 6, 8, 10};
int key = 8;
int index = binarySearch(arr, key);
if (index == -1) {
System.out.println("Element not found in array");
} else {
System.out.println("Element found at index " + index);
}
}
public static int binarySearch(int[] arr, int key) {
int left = 0;
int right = arr.length - 1;
while (left <= right) {
int mid = (left + right) / 2;
if (arr[mid] == key) {
return mid;
} else if (arr[mid] < key) {
left = mid + 1;
} else {
right = mid - 1;
}
}
return -1;
}
}
Element found at index 3
arr
and initialize it with the values 2, 4, 6, 8, and 10. We also declare an integer variable key
and initialize it with the value 8, which is the element we want to search for.binarySearch
method and pass the array and the key as arguments. This method performs a binary search on the array and returns the index of the first occurrence of the key, or -1 if the key is not found.(left + right) / 2
, and compare the element at the middle index with the key. If the middle element is equal to the key, we return its index. If the middle element is less than the key, we set the left endpoint to mid + 1
. If the middle element is greater than the key, we set the right endpoint to mid - 1
.-1
, we print "Element not found in array".