二分查找和数组合并

/**
* 数组合并
*/
public static int[] arrayMerge(int[] a, int[] b){
int[] c = new int[a.length + b.length];
int k=0,j=0,i=0;
while (k< a.length && j <b.length){
if (a[k] <= b[j]){
c[i] = a[k];
k++;
} else {
c[i] = b[j];
j++;
}
i++;
}
if (k == a.length){
for (int n = j; n < b.length; n++) {
c[k+n] = b[n];
}
} else {
for (int n = k; n < a.length; n++) {
c[k+n] = a[n];
}
}
return c;
}

/**
 * 二分法查找
 */
public static int binarySearch(int[] a, int x){
    return binarySearch(a, x, 0, a.length);
}

private static int binarySearch(int[] a, int x, int left, int right) {
    int high = right-1;
    while (left<=high){
        count++;
        int mid = (left + high)/2;
        int tem = a[mid];
        if (tem > x)
            high = mid-1;
        else if (tem < x)
            left = (mid+1);
        else
            return mid;
    }
    return -1;
}
posted @ 2017-12-16 11:27  SheaChen  阅读(182)  评论(0编辑  收藏  举报