我試圖用Java實現的二進制搜索:}定製二進制搜索中的ArrayIndesOutOfBoundsException?
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");
}
,而我得到了ArrayOutOfBoundsException中,我只是感到困惑,當我進入其不被發現的一個術語算法。
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)
對此的任何輸入將有所幫助。 謝謝:)
請添加行號。第32和42行是什麼? – Thilo 2012-03-11 07:04:19
您是否嘗試使用調試器進行調試? – home 2012-03-11 07:04:26