In: Computer Science
CODE :
public class Main
{
public static int BinarySearch(int arr[], int target, int low, int
high)
{
if(low > high) // target not found
{
return -1;
}
int mid = (low+high)/2;
if(target == arr[mid]) // target found
{
return mid;
}
if(target < arr[mid])
{
return BinarySearch(arr, target, low, mid-1); // target lies in the
left half
}
return BinarySearch(arr, target, mid+1, high); // target lies in
the right high
}
public static void main(String[] args) {
int[] arr = {1,2,3,4,5};
System.out.println("Index of 3: " +
BinarySearch(arr,3,0,4));
System.out.println("Index of 6: " +
BinarySearch(arr,6,0,4));
}
}
OUTPUT SNIPPET :
Hope this resolves your doubt, Please give an upvote if you liked my solution. Thank you :)