本帖最后由 奔跑的二叉树 于 2013-9-11 00:12 编辑
- import java.util.*;
- public class CollectionsDemo {
- public static void main(String[] args) {
- binarySearchDemo();
- }
- public static void binarySearchDemo()
- {
- List<String> list =new ArrayList<String>();
- list.add("aafasdfsdfsa");
- list.add("bbdfa");
- list.add("acdd");
- list.add("sddfaxdd");
- sop(list);
-
-
- int index=Collections.binarySearch(list,"acdd");
- sop("binarySearch查找的index="+index);
-
- int index1=halfSerach2(list,"acdd",new StrLenComparator());
- sop("我的二分法查找到的index为:"+index);
- }
- public static int halfSerach2(List<String> list,String key,Comparator<String> cmp)
- {
- int max,min,mid;
- max=list.size();
- min=0;
- mid=(max+min)>>1;
- while(min<=max)
- {
- String str=list.get(mid);
- int num=cmp.compare(str, key);
- if(num>0)
- max=mid-1;
- else if(num<0)
- min=mid+1;
- else
- return mid;
- }
- return -min-1;//返回-index-1
- }
- public static void sop(Object obj)
- {
- System.out.println(obj);
- }
- }
- class StrLenComparator implements Comparator<String>
- {
- public int compare(String s1,String s2)
- {
- if(s1.length()>s2.length())
- return 1;
- if(s1.length()<s2.length())
- return -1;
- return s1.compareTo(s2);
-
- }
- }
复制代码 按说是找不着才会返回一个负的啊
这个“acdd”怎么找不到呢,怎么会是-2呢,其他几个都是正数啊,这是什么情况呢? |