其实这个题目并不难,但是却是很实用,因为很多同学对于异常条件吃不准的话就会有问题。
看看JDK自带的二分查找吧
/**
* Searches a range of
* the specified array of longs for the specified value using the
* binary search algorithm.
* The range must be sorted (as
* by the {@link #sort(long[], int, int)} method)
* prior to making this call. If it
* is not sorted, the results are undefined. If the range contains
* multiple elements with the specified value, there is no guarantee which
* one will be found.
*
* @param a the array to be searched
* @param fromIndex the index of the first element (inclusive) to be
* searched
* @param toIndex the index of the last element (exclusive) to be searched
* @param key the value to be searched for
* @return index of the search key, if it is contained in the array
* within the specified range;
* otherwise, <tt>(-(