Why is this attempt at a binary search crashing?
Posted
by
Ian Campbell
on Stack Overflow
See other posts from Stack Overflow
or by Ian Campbell
Published on 2012-10-14T21:25:29Z
Indexed on
2012/10/14
21:37 UTC
Read the original article
Hit count: 317
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
© Stack Overflow or respective owner