本帖最后由 殷婷婷 于 2013-11-15 12:11 编辑
- import java.util.ArrayList;
- import java.util.Collections;
- import java.util.Comparator;
- import java.util.List;
- public class Test {
- public static void main(String[] args) {
- // TODO Auto-generated method stub
- List<String> list = new ArrayList<String>();
- list.add("java");
- list.add("demo");
- list.add("yinyi");
- list.add("zo");
- list.add("demo");
- Collections.sort(list,new StrLenComparator1());
- System.out.println(list);
- System.out.println(halfSearch2(list,"zo",new StrLenComparator1()));
- }
- public static int halfSearch2(List<String> list,String key,Comparator<String> cmp)
- {
- int min,max,mid;
- max = list.size()-1;
- min = 0;
- while(min<=max)
- {
- mid = (min+max)>>1;
- String str = list.get(mid);
- int num = cmp.compare(str,key);
- if(num>0)
- max = mid - 1;
- if(num<0)
- min = mid + 1;
- else return mid;
- }
- return -min-1;
- }
- }
- class StrLenComparator1 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);
- }
- }
-
复制代码 按照二分搜索法排序,System.out.println(halfSearch2(list,"zo",new StrLenComparator1()));的结果应该是0,可是运行了下,输出是2,实在找不出哪里错了,用binarySearch(list,"zo",new StrLenComparator()))输出的是正确的,肯定是程序哪儿写错了,麻烦帮我看一下,到底是哪儿的错。
|