二分查找发

public class sf {

    /**
     * @param args
     */
    public static void main(String[] args) {
        int[] arr = { 2, 5, 9, 56 };
        int a = halfserach(arr, 56);
        // TODO Auto-generated method stub

        System.out.println(a);

    }

    public static int halfserach(int[] arr, int tagert) {
        int max = arr.length - 1;
        int min = 0;
        int mid = (max + min) / 2;
        while (true)

        {
            if (tagert > arr[mid]) {
                min = mid + 1;
            } else if (tagert < arr[mid]) {
                max = mid - 1;

            }

            else {
                return mid;
            }
            if (max < min) {

                return -1;
            }
            mid = (max + min) / 2;

        }

    }

}

 

posted @ 2016-02-18 19:37  刀小爱  阅读(101)  评论(0编辑  收藏  举报