首页 > 代码库 > 二分查找

二分查找


    /**
     * 二分查找
     * @param searchNum 查找数据
     * @param lists 查找队列
     * @return false 没找到  true 找到
     */
    public static boolean search(int searchNum, List<Integer> lists){
        boolean flag = false;
        try{
            int length = 0;  //数据链表长度
                if(null != lists && 0 < (length=lists.size())){
                    if(1 == length){
                        if(searchNum == lists.get(0)){
                            return true;
                        }
                    }else{
                        int segmentationPoint = length/2; //分割点
                        int tempObj = lists.get(segmentationPoint); //获取分割点位置数据
                        if(searchNum == tempObj){ //如果获取的数据等于查找的数据
                            return true;
                        }else if(searchNum>tempObj){ //如果获取的数据小于查找的数据
                            List<Integer> tempList = new ArrayList<Integer>(); //存储零时数据
                            for(int i=segmentationPoint+1;i<length;i++){
                                tempList.add(lists.get(i));    
                            }
                            flag = search(searchNum, tempList); //回调函数
                        }else{//如果获取的数据大于查找的数据
                            List<Integer> tempList = new ArrayList<Integer>(); //存储零时数据
                            for(int i=0;i<segmentationPoint;i++){
                                tempList.add(lists.get(i));    
                            }
                            flag = search(searchNum, tempList); //回调函数
                        }
                    }
                }
        }catch (Exception e) {
            System.out.println(e.getMessage());
        }
        return flag;
    }

本文出自 “最美谎言” 博客,请务必保留此出处http://wumingfeixue.blog.51cto.com/10417767/1881273

二分查找