1. Test equal at last setp.
public static int binarySearch(int[] sorted, int first, int upto, int key) { while (first < upto) { int mid = (first + upto) / 2; // Compute mid point. if (key < sorted[mid]) { upto = mid; // repeat search in bottom half. } else if (key > sorted[mid]) { first = mid + 1; // Repeat search in top half. } else { return mid; // Found it. return position } } return -(first + 1); // Failed to find key}Read full article from Java Notes: Algorithms: Binary Search