After running a program, it directed me to If (key.compareTo(a[mid]) == 0)
What's wrong with it?
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 5 at BinarySearch.search(BinarySearch.java:17) at SearchesDemo.main(SearchesDemo.java:23)
import java.util.Scanner;
import java.util.Arrays;
public class SearchesDemo{
public static void main(String[] args){
BinarySearch searches = new BinarySearch();
int result, key;
Integer [] integerArray = {0, 2, 4, 6, 8, 10, 12, 14, 16, 18};
String [] stringArray = {"apples", "oranges", "peaches", "strawberries", "watermelons"};
System.out.println("Integer test array contains:");
System.out.println(Arrays.toString(integerArray));
for(key = -3; key == 4; key++){
result = searches.<Integer>search(integerArray, 0, 10, key);
searches.toString(Integer.toString(key), result);
}
System.out.println("\nString test array contains:");
System.out.println(Arrays.toString(stringArray)); //toString may not be necessary
result = searches.<String>search(stringArray, 0, 10, "apples");
searches.toString("apples", result);
result = searches.<String>search(stringArray, 0, 10, "plums");
searches.toString("plums", result);
System.out.println("\nProcess completed.");
}
}
public class BinarySearch{
public static <T extends Comparable> int search(T [] a, int first, int last, T key){
int result = 0; //to keep the compiler happy.
if (first > last)
result = -1;
else{
int mid = (first + last)/2;
if (key.compareTo(a[mid]) == 0)
result = mid;
else if (key.compareTo(a[mid]) < 0)
result = search(a, first, mid - 1, key);
else if (key.compareTo(a[mid]) > 0)
result = search(a, mid + 1, last, key);
else{
System.out.println("Error");
result = -1;
}
}
return result;
}
public static void toString(String key, int result){
if(result == -1)
System.out.println(key + " is not in the array.");
else
System.out.println(key + " is at index " + result);
}
}