二分查找


    /**
     * 二分查找
     * @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;
    }

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章