algorithm@ lower_bound implementation(Binary Search)

一道来自jhu algorithm的作业题:

Given two sorted arrays A, B, give a linear time algorithm that finds two entries i,j such that|A[i]−B[j]|is minimized. Prove the correctness of your algorithm and analyze the running time.

Solution:我们可以对于每个a[i],然后再B数组中二分查找距离a[i] “最近”的数,这里的“最近”是指|A[i]−B[j]|最小。

贴上一个algo代码 和 一个简单test案例。

package abc.com;

import java.util.Collections;

public class TestLowerBound {
    
    public static void prt(Object o) {
        System.out.print(o);
    }
    
    //return a index where (key <= a[index])
    public static int lowerBound(int[] a, int key) {
        int l = 0, r = a.length-1, mid;
        if(key > a[r])  return -1;
        
        while(l < r) {
            mid = (l+r)/2;
            if(a[mid] < key)  l = mid + 1;
            else r = mid;
        }
        
        return l;
    }
    
    public static int min_abs_dif(int[] a, int val) {
        int l = 0, r = a.length-1, mid;
        
        if(val <= a[l]) {
            return Math.abs(val - a[l]);
        }
        else if(val >= a[r]) {
            return Math.abs(val - a[r]);
        }
        else {
            int pos = lowerBound(a, val);
            //prt(pos);
            if(Math.abs(a[pos] - val) == 0)  return 0;
            int min = Integer.MAX_VALUE;
            if(pos-1 >= 0 && Math.abs(a[pos-1] - val) < min)  min = Math.abs(a[pos-1] - val);
            if(pos >= 0 && (Math.abs(a[pos] - val) < min))  min = Math.abs(a[pos] - val);
            return min;
        }
        
    }
    
    public static void main(String[] args) {
        int[] a = {1, 29, 32, 42, 61, 63, 64, 84, 88, 99};
        
        /*
        for(int i=0; i<a.length; ++i) {
            a[i] = (int)(Math.random() * 100);
            prt(a[i] + "   ");
        }*/
        
        int min_abs = min_abs_dif(a, 450); 
        prt("
" + min_abs);
    }

}
原文地址:https://www.cnblogs.com/fu11211129/p/5182600.html