Monday, November 16, 2015

tertiary search - find left open and left close in a sorted list

In a typical binary search, we search the half based on the comparison result between middle point and target until there is nothing to search, we return the index if middle number is equal to target, if not found, we return -1.

In proximity search which tries to find the number with smallest index which is larger or equal to target, we use ternary search, which narrows down the search range to two numbers.

Here is the algorithm:

/*
     * find left-most number which is larger or equal to target
     */
    public static int leftOpen(int[] sorted, int target){
        int left = 0, right = sorted.length -1 ;
        while(right - left > 1){
            int mid = (right + left) >>> 1;
            if(sorted[mid]<target)
                left = mid + 1 ;
            else
                right = mid;
        }
       
        return sorted[left]>=target?left:right;
    }

    /*
     * find left-most number which is larger than target
     */
    public static int leftClose(int[] sorted, int target){
        int left = 0, right = sorted.length -1 ;
        while(right - left > 1){
            int mid = (right + left) >>> 1;
            if(sorted[mid]<=target)
                left = mid + 1;
            else
                right = mid;
        }
       
        return sorted[left]>target?left:right;
    }

No comments:

Post a Comment