publicclassBinarySearch {
publicstaticvoidmain(String[] args) {
int[] sortedArray = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
int target = 6;
int result = binarySearch(sortedArray, target);
if (result != -1) {
System.out.println("Element found at index " + result);
} else {
System.out.println("Element not found in the array.");
}
}
publicstaticintbinarySearch(int[] arr, int target) {
int left = 0;
int right = arr.length - 1;
while (left <= right) {
int mid = left + (right - left) / 2;
if (arr[mid] == target) {
return mid; // Element found
} elseif (arr[mid] < target) {
left = mid + 1; // Search the right half
} else {
right = mid - 1; // Search the left half
}
}
return-1; // Element not found
}
}