binary search Template

Binary search is a famous question in algorithm. For a given sorted array (ascending order) and a target number, find the first index of this number in O(log n) time complexity. If the target number does not exist in the array, return -1. Example If the array is [1, 2, 3, 3, 4, 5, 10], for given target 3, return 2.

public class BinarySearch {
    public int binarySearch(int[] A, int target) {
        if (A.length == 0)
            return -1;
        int start = 0;
        int end = A.length - 1;
        int mid;

        while (start + 1 < end) {
            mid = start + (end - start) / 2;
            if (A[mid] == target)
                end = mid;
            else if (A[mid] < target)
                start = mid;
            else if (A[mid] > target)
                end = mid;
        }

        if (A[start] == target)
            return start;
        if (A[end] == target)
            return end;
        return -1;
    }
}

http://lintcode.com/zh-cn/tag/binary-search/ 

posted on 2015-02-07 17:08  lh_chuang  阅读(126)  评论(0)    收藏  举报

导航