最も簡単なアルゴリズム-二分検索


JAvaコード
/**
 * Created by fupeng on 2017/1/11.
 */
public class binarySearch {

    public static long binarySearch_a(long [] src, int key){
        int lo = 0;
        int hi = src.length-1;
        while(lo <= hi){
            int mid = lo + (hi-lo)/2;
            if(key < src[mid]){
                hi = mid-1;
            }else if(key > src[mid]){
                lo = mid+1;
            }else{
                return mid;
            }
        }

        return  -1;
    }
    public static void main(String [] argv){
        System.out.println("hello world");
        long [] src = {1,2,4,67,89,100,291};
        for (long a : src){
            System.out.println(a);
        }

        long find = binarySearch_a(src, 292);
        if(find < 0) {
            System.out.println("not found");
        }else{
            System.out.println(" found");
        }
    }
}

二分検索の条件は、整列したリストです.