复杂度 O(lgN)
使用条件:数据已经排序并在内存中。
package chapter1; public class BinarySearch <T>{ public static <T extends Comparable<? super T>> int binarySearch(T [] a, T x){ int low =0; int high = a.length-1; while (low<= high){ int mid =(low+high)/2 ; if (a[mid].compareTo(x)<0){ low = mid+1; }else if (a[mid].compareTo(x)>0) { high= mid-1; }else { return mid; } } return -1; //not found } }