分表路由實現僞代碼

根據Id分段實現分表路由的核心僞代碼實現

這裏寫圖片描述

核心僞代碼如下

1、二分查找算法:

    public static int binarySearch(byte[] a, byte key) {
        return binarySearch0(a, 0, a.length, key);
    }

    // Like public version, but without range checks.
    private static int binarySearch0(byte[] a, int fromIndex, int toIndex,
                                     byte key) {
        int low = fromIndex;
        int high = toIndex - 1;

        while (low <= high) {
            int mid = (low + high) >>> 1;
            byte midVal = a[mid];

            if (midVal < key)
                low = mid + 1;
            else if (midVal > key)
                high = mid - 1;
            else
                return mid; // key found
        }
        return -(low + 1);  // key not found.
    }

2、檢索路由key

    //根據期Id 查找路由區間 拼接成字符串返回
    private String searchIssueIdLoction(long[] arr, long issueId) {
        // 獲取期Id索引位置
        int index = getIndex(arr, issueId);
        // 小於0的情況出現頻次高
        if (index < 0) {
            return arr[Math.abs(index) - 2] + SEPARATOR + arr[Math.abs(index) - 1];
        }
        if (isEven(index)) {
            return arr[Math.abs(index)] + SEPARATOR + arr[Math.abs(index + 1)];
        }
        return arr[Math.abs(index) - 1] + SEPARATOR + arr[Math.abs(index)];
    }

    //是偶數
    private boolean isEven(int index) {
        return index % 2 == 0;
    }
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章