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

2017-08-28  本文已影响0人  KavinDotG

废话不多说,上代码

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));
    }
}

上一篇下一篇

猜你喜欢

热点阅读