数组拷贝,二分法查找-成都快上网建站

数组拷贝,二分法查找

Arrays.copyOfRange(int[] arr,int开始下标,int结束下标)//左闭右开
System.arraycopy(int[] source,int开始下标,int[] dest,int开始下标,int拷贝多少个)

这里是手动拷贝:
public static int[] copyOf(int[] original, int newLength) {
    int[] dest = new int[newLength];
    int length = original.length <= newLength ? original.length : newLength;
    for (int i = 0; i < length; i++) {
        dest[i] = original[i];
    }

    return dest;
}

mid作为分水岭,  不断地缩小范围
// 前提需要数组是有序的
public static int binarySearch(int[] a, int v) {
    int left = 0;
    int right = a.length;

    while (left < right) {
        int mid = (left + right) / 2;
        if (v == a[mid]) {
            return mid;
        } else if (v < a[mid]) {
            right = mid;
        } else {
            left = mid + 1;
        }
    }

    return -1;
}

public static int binarySearch3(int[] a, int v) {
    int left = 0;
    int right = a.length - 1;

    while (left <= right) {
        int mid = (left + right) / 2;
        if (v == a[mid]) {
            return mid;
        } else if (v < a[mid]) {
            right = mid - 1;
        } else {
            left = mid + 1;
        }
    }

    return -1;
}

分享文章:数组拷贝,二分法查找
URL地址:http://kswjz.com/article/jhjdie.html
扫二维码与项目经理沟通

我们在微信上24小时期待你的声音

解答本文疑问/技术咨询/运营咨询/技术建议/互联网交流