/*Collections.实现Comparator比较器进行二分查找
Collections 集合框架的工具类
*/
import java.util.*;
class CollectionsDemo
{
public static void main(String[] args)
{
sortDemo();
}
public static void binarySearchDemo(){
List<String> list = new ArrayList<String>();
list.add("abcd");
list.add("aaa");
list.add("zz");
list.add("kkkkk");
list.add("qq");
list.add("z");
Collections.sort(list);
sop(list);
int index = Collections.binarySearch(list,"aaa");
sop("index="+index);
}
public static int halfSearch(List<String> list,String key,Comparator<String>){
int max,min,mid;
max = list.size()-1;
min = 0;
while (min<=max)
{
mid = (max+min)>>1;// 右移1位,相当于/2;
String str = list.get(mid);//获取mid 角标对应的key
//int num = str.compareTo(key);//拿key判断 str
int num = cmp.compare(str,key);//拿key判断 str
if(num>0)
max = mid -1;
else if(num<0)
min = mid +1;
else
return mid;
}
return -min-1;
}
public static void maxDemo(){
List<String> list = new ArrayList<String>();
list.add("abcd");
list.add("aaa");
list.add("zz");
list.add("kkkkk");
list.add("qq");
list.add("z");
Collections.sort(list);
sop(list);
String max = Collections.max(list);
sop("max="+max);
}
public static void sortDemo()
{
//创建一个集合容器.使用Collection接口的子类List
List<String> list = new ArrayList<String>();
list.add("abcd");
list.add("aaa");
list.add("zz");
list.add("kkkkk");
list.add("qq");
list.add("z");
sop(list);
Collections.sort(list, new StrLenComparator());
sop(list);
}
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);
}
}
Collections.sort方法实现Comparator比较器进行二分查找
最新推荐文章于 2024-01-02 22:53:17 发布