美文网首页
二分法查找,效率杠杠的,java版

二分法查找,效率杠杠的,java版

作者: KavinDotG | 来源:发表于2017-08-28 18:23 被阅读0次

    废话不多说,上代码

    import java.util.ArrayList;
    import java.util.List;
    
    public class BinarySearch {
        
        public static Integer binarySearch(List<Integer> list,Integer num){
            Integer low = 0;
            Integer high = list.size()-1;
            Integer counter = 0;
            while(low <= high){
                Integer mid = (low + high)/2;
                Integer guess = list.get(mid);
                if(guess == num){
                    return guess;
                }else if(guess >= num){
                    high = mid - 1;
                }else{
                    low = mid + 1;
                }
                System.out.println("low:"+low);
                System.out.println("high:"+high);
                ++counter;
            }
            return counter;
        }
        
        public static void main(String[] args) {
            List<Integer> list = new ArrayList<>();
            for(int x=1; x<1000000; x++){
                list.add(x);
            }
            System.out.println(BinarySearch.binarySearch(list, 356));
        }
    }
    
    

    相关文章

      网友评论

          本文标题:二分法查找,效率杠杠的,java版

          本文链接:https://www.haomeiwen.com/subject/akigdxtx.html