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