一.while条件:while(low <= high).最简单的可以向,如果最后剩下一个元素进行比较,如果条件为low < high,则不会进入比较,从而得不到结果
二.对于Comparable这个类中,对两个元素进行比较,使用val1.compareTo(val2)方法(当然气候要对compareTo方法进行重写),val1==val2,return 0;val1 < val2,return - 1;val1 > val2,return 1;
三.注意low = center + 1和high = center - 1;
1 public class BinarySeacher { 2 public static final int NOT_FOUND = -1; 3 public static <AnyType extends Comparable<? super AnyType>> int binarySeacher(AnyType [] a, AnyType x){ 4 int low = 0,high = a.length - 1; 5 6 while(low <= high ){ 7 int center = ( low + high ) / 2; 8 if(a[center].compareTo(x) < 0) 9 low = center + 1; 10 else if(a[center].compareTo(x) > 0) 11 high = center - 1; 12 else 13 return center; 14 } 15 16 return NOT_FOUND; 17 } 18 }