Java 二分查找的简单使用

来源:互联网 发布:it程序员招聘 编辑:程序博客网 时间:2024/06/06 00:34

Java 二分查找的简单使用

用了很久的C++,最近开始比较深入的了解JAVA,越来越发现JAVA真是一种非常方便的语言!比如说这里要说的的二分查找算法,现在的项目里面有个队列查找,需要使用二分查找算法来进行简单的实现。本来想着会比较麻烦的,结果发现JAVA库里面已经帮我们把这个算法实现了,直接拿出来用就可以了。下面是使用示例:

代码块

public List<Located> getLocatedObjectByCoords(Point point) {    List<Located> result = new ArrayList<Located>();    //库位    Comparator<Grid> comparator = new Comparator<Grid>(){        @Override        public int compare(Grid grid1, Grid grid2) {            int first = grid1.getColumnIndex() - grid2.getColumnIndex();            return 0 == first ? grid1.getRowIndex() - grid2.getRowIndex() : first;        }    };    ///如果没有排序则进行排序    if(gridsSortedByColumnAndRow == null){        gridsSortedByColumnAndRow = new ArrayList<Grid>(this.getWarehouse().getGrids().values());        gridsSortedByColumnAndRow.sort(comparator);    }    int index = Collections.binarySearch(gridsSortedByColumnAndRow, new Grid(point), comparator);    if(index >= 0){        result.add(gridsSortedByColumnAndRow.get(index));    }    return result;}
0 0