java - While loop doesnt end in iterative binary search -
i'm writing binary search uses iteration instead of recursion , not returning anything. i've debugged down while loop not ending can't seem figure out went wrong.
here 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, list ordered ;)
in second else if part need set last instead of first -
else if(obj.compareto(array[middle]) < 0) last = middle - 1;
Comments
Post a Comment