本帖最后由 t_mac 于 2011-12-12 15:23 编辑
import java.util.*;
public class CollectionsDemo {
public static void main(String[] args) {
List<String> al = new ArrayList<String>();
al.add("abc");
al.add("z");
al.add("qq");
al.add("kkkkk");
al.add("aaaa");
Collections.sort(al);
System.out.println(al);
int index =halfSearch(al,"aaa");
System.out.println(index);
}
public static int halfSearch(List<String> list,String s){
int min = 0,max = list.size()-1;
int mid = 0;
while(min<max){
mid = (min+max)>>1;
String str = list.get(mid);
int num = str.compareTo(s);
if(num<0)
min = mid+1;
else if(num>0)
max = mid-1;
else
return mid;
}
return -min-1;
}
}
最后一个return返回的是-(插入点)-1 那这里的min就是插入点,为什么插入点是min啊? |