Monday, November 16, 2015

find insert position in a sorted list

One of the JDK's array utility function binary is to not only find the target, but also return the insertion position if the target is not found.
For its javadoc, look at this link:
http://docs.oracle.com/javase/7/docs/api/java/util/Arrays.html#binarySearch%28int[],%20int%29

Here is the two implementation.

The first solution is to narrow down the search window to size of 2. And second solution is to narrow down search window to size of 1.

    public static int findInsertPos(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;
        }
       
        if(sorted[left] == target)
            return left;
        if(sorted[right] == target)
            return right;
        if(sorted[left] > target)
            return left;
        return sorted[right]>target?right:right+1;
    }
   
    public static int findInsertPos2(int[] sorted, int target){
        int left = 0, right = sorted.length ;
        while(right > left){
            int mid = (right + left) >>> 1;
            if(sorted[mid] == target)
                return mid;
            if(sorted[mid]<target)
                left = mid + 1 ;
            else
                right = mid;
        }
        if(left == sorted.length || sorted[left] >= target)
            return left;
        return left+1;
    }

No comments:

Post a Comment