數組拷貝,二分法查找

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 binarySearch2(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;
}
相關文章
相關標籤/搜索