I am fairly new to the concept of a binary search, and am trying to write a program that does this in Java for personal practice. I understand the concept of this well, but my code is not working.
There is a run-time exception happening in my code that just caused Eclipse, and then my computer, to crash... there are no compile-time errors here though.
Here is what I have so far:
public class BinarySearch
{
// instance variables
int[] arr;
int iterations;
// constructor
public BinarySearch(int[] arr)
{
this.arr = arr;
iterations = 0;
}
// instance method
public int findTarget(int targ, int[] sorted)
{
int firstIndex = 1;
int lastIndex = sorted.length;
int middleIndex = (firstIndex + lastIndex) / 2;
int result = sorted[middleIndex - 1];
while(result != targ)
{
if(result > targ)
{
firstIndex = middleIndex + 1;
middleIndex = (firstIndex + lastIndex) / 2;
result = sorted[middleIndex - 1];
iterations++;
}
else
{
lastIndex = middleIndex + 1;
middleIndex = (firstIndex + lastIndex) / 2;
result = sorted[middleIndex - 1];
iterations++;
}
}
return result;
}
// main method
public static void main(String[] args)
{
int[] sortedArr = new int[]
{
1, 3, 5, 7, 9, 11, 13, 15, 17, 19, 21, 23, 25, 27, 29
};
BinarySearch obj = new BinarySearch(sortedArr);
int target = sortedArr[8];
int result = obj.findTarget(target, sortedArr);
System.out.println("The original target was -- " + target + ".\n" +
"The result found was -- " + result + ".\n" +
"This took " + obj.iterations + " iterations to find.");
} // end of main method
} // end of class BinarySearch