It throws error ArrayIndexOutOfBound, when i try to search an element which is out of the range of given input array.
Below is the code snippet:
import java.util.*;
public class Binary {
int binSearch(int arr[], int target)
{
int low=0;
int high= arr.length;
while(low<=high)
{
int mid = (low+high)/2;
if(arr[mid] == target)
return mid;
if(target>arr[mid])
low=mid+1;
else
high=mid-1;
}
return -1;
}
public static void main(String arg[])
{
Binary b= new Binary();
int arr[]= {2, 4, 5, 7, 23, 31, 34, 43, 45};
int ans=b.binSearch(arr, 46);
if(ans==-1)
System.out.println("The element is not found");
else
System.out.println("Element is found at postion = " + (ans+1));
}
}