I am trying to implement binary search in Java:
import java.util.Scanner;
public class Search
{
public static void sequential_search(int[] array,int search_variable)
{
boolean flag = false;
for(int loop=0;loop<array.length;loop++)
{
if(array[loop] == search_variable)
{
flag = true;
break;
}
}
if(flag == true)
System.out.println("The value is present");
else
System.out.println("The value is absent");
}
public static int binary_search_recursive(int[] array,int low,int high,int search_variable)
{
if(low > high)
{
return 0;
}
else
{
int mid;
mid = (low+high)/2;
if(array[mid] == search_variable)
{
return 1;
}
else if (array[mid] > search_variable)
{
return binary_search_recursive(array, low, mid - 1, search_variable);
}
else
{
return binary_search_recursive(array, mid + 1, high, search_variable);
}
}
}
public static void main(String[] args)
{
int[] array = {10, 9, 8, 7, 6, 5, 4, 3, 2, 1};
int search_variable;
System.out.println("Please enter the number to be search:");
Scanner number = new Scanner(System.in);
search_variable = number.nextInt();
System.out.println("The number to be searched is "+search_variable);
//sequential_search(array,search_variable);
if ((binary_search_recursive(array, 0, array.length, search_variable)) == 0)
System.out.println("The value is present");
else
System.out.println("The value is absent");
}
}
I’m just getting confused while I’m getting out of ArrayOutOfBoundsException, when I enter a term which is not found by the algorithm.
Please enter the number to be search:
12
The number to be searched is 12
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 10
at Search.binary_search_recursive(Search.java:32)
at Search.binary_search_recursive(Search.java:42)
at Search.binary_search_recursive(Search.java:42)
at Search.binary_search_recursive(Search.java:42)
at Search.main(Search.java:59)
Any input on this would be helpful.
Thanks 🙂
I think that the issue here is that your
lowandhighvariables represent the range [low, high), with thehighvalue excluded. This means that your base case, which is currentlyshould probably be
Since if you have the range [low, low), there aren’t any elements left. Requiring
low > highbefore you terminate means that you will need low to actually exceedhigh, which shouldn’t be possible.If I’m correct about this, this also means that one of your recursive calls to the function has the wrong upper bound. Specifically, this code:
should be
since if
highis exclusive, passing inmidas the upper bound is the proper way to get everything up to but not including the middle value.Hope this helps!