1. 程式人生 > >data_structure_and_algorithm -- 4種常見二分查詢變形問題

data_structure_and_algorithm -- 4種常見二分查詢變形問題

二分查詢變形問題:

(1)查詢第一個值等於給定值的元素

(2)查詢最後一個值等於給定值的元素

(3)查詢第一個大於等於給定值的元素

(4)查詢最後一個小於等於給定值的元素

//(1)查詢第一個值等於給定值的元素
public int bsearch1(int[] a, int n, int value){
    int low = 0;
    int high = n-1;
    while (low<=high){
        int mid = low + ((high - low) >> 1);
        if (a[mid] > value){
            high = mid - 1;
        }else if (a[mid]<value){
            low = mid + 1
        }else{
            if ((mid == 0) || (a[mid-1] != value)) return mid;
            else high = mid - 1;
        }
    }
    return -1;
}

//(2)查詢最後一個值等於給定值的元素
public int bsearch2(int[] a, int n, int value){
    int low = 0;
    int high = n-1;
    while (low<=high){
        int mid = low + ((high - low) >> 1);
        if (a[mid] > value){
            high = mid - 1;
        }else if (a[mid]<value){
            low = mid + 1
        }else{
            if ((mid == n-1) || (a[mid+1] != value)) return mid;
            else low = mid + 1;
        }
    }
    return -1;
}

//(3)查詢第一個大於等於給定值的元素
public int bsearch3(int[] a, int n, int value){
    int low = 0;
    int high = n-1;
    while (low<=high){
        int mid = low + ((high - low) >> 1);
        if (a[mid] >= value){
            if ((mid==0 || a[mid-1] < value)) return mid;
            else high = mid - 1;
        }else{
            low = mid + 1
        }
    }
    return -1;
}

//(4)查詢最後一個小於等於給定值的元素
public int bsearch4(int[] a, int n, int value){
    int low = 0;
    int high = n-1;
    while (low<=high){
        int mid = low + ((high - low) >> 1);
        if (a[mid] > value){
            high = mid - 1; 
        }else {
            if ((mid==n-1 || a[mid+1] > value)) return mid;
            else low = mid + 1;
        }
    }
    return -1;
}