I was implementing a code for binary search in an array in java here is my code:
public class Exam {
public static boolean find(int[]a, int k){
int mid = a.length/2;
if (a[mid]==k) {
return true;
}
else if (a[mid] < k) {
for (int i=0; i<a[mid]; i++) {
if (a[i]==k) {
return true;
}
}
} else {
for (int ii=mid; ii<a[a.length]; ii++) {
if (a[ii]==k) {
return true;
}
}
}
return false;
}
public static void main(String[] args) {
int[] a = { 2, 3, 4, 9, 11, 15 };
System.out.println(find(a,3));
}
}
When I run it I get error:
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 6
at shapes.Exam.find(Exam.java:20)
at shapes.Exam.main(Exam.java:34)
But when I run this line instead:
System.out.println(find(a,15));
I get correct output as following:
true
What is the wrong with my code?