本帖最后由 程序爱好者 于 2014-4-17 10:50 编辑
- import java.util.*;;
- public class Test {
- public static void main(String[] args) {
- List<String> list=new ArrayList<String>();
- list.add("abcfdsfdsf");
- list.add("cdtw");
- list.add("da");
- list.add("da");
- list.add("dd");
- list.add("zbcfd");
- // Collections.sort(list);
- sop(list);
- // int index=halfSearch(list,"cdtwa");
- int index=halfSearch(list,"cdtw",new com());
- sop("index="+index);
- }
- public static int halfSearch(List<String> list,String key,Comparator<String> com)//这方法下面的代码怎么理解?
- {
- int max,min,mid;
- max=list.size()-1;
- min=0;
- while(min<=max)
- {
- mid=(max+min)>>1;
- String str=list.get(mid);
- int num=str.compareTo(key);
- if (num>0) {
- max=mid-1;
- }else if (num<0) {
- min=min+1;
- }else{
- return mid;
- }
- }
- return -min-1;
-
- }
- public static void sop(Object obj)
- {
- System.out.println(obj);
- }
-
- }
复制代码
谁能给我详细的说一下那个折半的原理 |