兩個數組A,B取差的絕對值的最小值,性能有待測試

public int smallestDifference(int[] A, int[] B) {
       //希爾排序數組B數組

       int step =50;
        if(B!=null && B.length>1){
            step = step/2;
            while(step>0){
                for(int i =step;i< B.length;i++){
                    int key = B[i];
                    int j;
                    for(j=i-step;j>=0 && j<B.length; ){
                        if(key<B[j]){
                            B[j+step]=B[j];
                            j =j-step;
                        }else{
                            break;
                        }
                    }
                    B[j+step]=key;
                }
                step = step/2;
            }
        }
        //取最中間的2個數
        int tmp = Integer.MAX_VALUE;
        for(int i=0;i<A.length;i++){
            int round =0;
            int left =0;
            int right = B.length-1;
            int mid=0;
             while (left <= right) {
                          mid = (left + right) / 2;
                         if (A[i] < B[mid]) {//i在左邊
                             right = mid - 1;
                             round =1;
                         } else if (B[mid] < A[i]) {//i在右邊
                             left = mid + 1;
                             round =2;
                         } else {
                             round =0;
                             break;
                        }
                    }
             if(round ==0) {
                 tmp =0;
                 break;
             }
             if(round ==1) {
                int tmp1 = Math.abs(A[i]-B[mid]);
                int tmp2 = Math.abs(A[i]-B[mid>0?mid-1:mid]);
                int    tmp3 = tmp1>tmp2?tmp2:tmp1;
                tmp = tmp>tmp3?tmp3:tmp;
             }
             if(round ==2) {
              int tmp1 = Math.abs(A[i]-B[mid]);
              int tmp2 = Math.abs(A[i]-B[mid<B.length-1?mid+1:mid]);
              int tmp3 = tmp1>tmp2?tmp2:tmp1;
              tmp = tmp>tmp3?tmp3:tmp;
             }
        }
        return tmp;排序

    }while

相關文章
相關標籤/搜索