I'm currently writing a binary search that uses iteration instead of recursion and its not returning anything. I've debugged it down to the while loop not ending but I can't seem to figure out where I went wrong.
Here is the code:
public static <E extends Comparable> boolean binarySearchIterative(E[] array, E obj) {
int first = 0;
int last = array.length - 1;
while(first <= last) {
int middle = (first + last) / 2;
if(array[middle].equals(obj)) return true;
else if(obj.compareTo(array[middle]) < 0) first = middle - 1;
else first = middle + 1;
}
return false;
}
And yes, my list is ordered ;)
middle + 1would never become greater thanlastelse ifshould belast = middle -1;Not first.