public class Main {
public static void main
(String[] args
) { int[] sortedArray = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
int target = 6;
int result = binarySearch(sortedArray, target, 0, sortedArray.length - 1);
if (result != -1) {
System.
out.
println("Element " + target
+ " found at index " + result
); } else {
System.
out.
println("Element " + target
+ " not found in the array"); }
}
// Recursive Binary Search function
static int binarySearch(int[] arr, int target, int low, int high) {
if (low <= high) {
int mid = low + (high - low) / 2;
// If the target is present at the middle
if (arr[mid] == target) {
return mid;
}
// If the target is smaller than the middle element, search in the left subarray
if (arr[mid] > target) {
return binarySearch(arr, target, low, mid - 1);
}
// If the target is larger than the middle element, search in the right subarray
return binarySearch(arr, target, mid + 1, high);
}
// If the target is not present in the array
return -1;
}
}
cHVibGljIGNsYXNzIE1haW4gewoKICAgIHB1YmxpYyBzdGF0aWMgdm9pZCBtYWluKFN0cmluZ1tdIGFyZ3MpIHsKICAgICAgICBpbnRbXSBzb3J0ZWRBcnJheSA9IHsxLCAyLCAzLCA0LCA1LCA2LCA3LCA4LCA5LCAxMH07CiAgICAgICAgaW50IHRhcmdldCA9IDY7CgogICAgICAgIGludCByZXN1bHQgPSBiaW5hcnlTZWFyY2goc29ydGVkQXJyYXksIHRhcmdldCwgMCwgc29ydGVkQXJyYXkubGVuZ3RoIC0gMSk7CgogICAgICAgIGlmIChyZXN1bHQgIT0gLTEpIHsKICAgICAgICAgICAgU3lzdGVtLm91dC5wcmludGxuKCJFbGVtZW50ICIgKyB0YXJnZXQgKyAiIGZvdW5kIGF0IGluZGV4ICIgKyByZXN1bHQpOwogICAgICAgIH0gZWxzZSB7CiAgICAgICAgICAgIFN5c3RlbS5vdXQucHJpbnRsbigiRWxlbWVudCAiICsgdGFyZ2V0ICsgIiBub3QgZm91bmQgaW4gdGhlIGFycmF5Iik7CiAgICAgICAgfQogICAgfQoKICAgIC8vIFJlY3Vyc2l2ZSBCaW5hcnkgU2VhcmNoIGZ1bmN0aW9uCiAgICBzdGF0aWMgaW50IGJpbmFyeVNlYXJjaChpbnRbXSBhcnIsIGludCB0YXJnZXQsIGludCBsb3csIGludCBoaWdoKSB7CiAgICAgICAgaWYgKGxvdyA8PSBoaWdoKSB7CiAgICAgICAgICAgIGludCBtaWQgPSBsb3cgKyAoaGlnaCAtIGxvdykgLyAyOwoKICAgICAgICAgICAgLy8gSWYgdGhlIHRhcmdldCBpcyBwcmVzZW50IGF0IHRoZSBtaWRkbGUKICAgICAgICAgICAgaWYgKGFyclttaWRdID09IHRhcmdldCkgewogICAgICAgICAgICAgICAgcmV0dXJuIG1pZDsKICAgICAgICAgICAgfQoKICAgICAgICAgICAgLy8gSWYgdGhlIHRhcmdldCBpcyBzbWFsbGVyIHRoYW4gdGhlIG1pZGRsZSBlbGVtZW50LCBzZWFyY2ggaW4gdGhlIGxlZnQgc3ViYXJyYXkKICAgICAgICAgICAgaWYgKGFyclttaWRdID4gdGFyZ2V0KSB7CiAgICAgICAgICAgICAgICByZXR1cm4gYmluYXJ5U2VhcmNoKGFyciwgdGFyZ2V0LCBsb3csIG1pZCAtIDEpOwogICAgICAgICAgICB9CgogICAgICAgICAgICAvLyBJZiB0aGUgdGFyZ2V0IGlzIGxhcmdlciB0aGFuIHRoZSBtaWRkbGUgZWxlbWVudCwgc2VhcmNoIGluIHRoZSByaWdodCBzdWJhcnJheQogICAgICAgICAgICByZXR1cm4gYmluYXJ5U2VhcmNoKGFyciwgdGFyZ2V0LCBtaWQgKyAxLCBoaWdoKTsKICAgICAgICB9CgogICAgICAgIC8vIElmIHRoZSB0YXJnZXQgaXMgbm90IHByZXNlbnQgaW4gdGhlIGFycmF5CiAgICAgICAgcmV0dXJuIC0xOwogICAgfQp9