首页 > 代码库 > 二分查找函數

二分查找函數

找到,返回下標;

int binary_search(const int* a, int low_position, int high_position, const int key)
{
    high_position--;
    while(low_position < high_position) {
        int mid_position = (low_position+high_position) >> 1;
        if(a[mid_position] == key) return mid_position;
        else if(a[mid_position] < key) low_position = mid_position + 1;
        else high_position = mid_position - 1;
    }
    return -1;
}

找到,返回success

char* binary_search(const int* a, int low_position, int high_position, const int key)
{
    high_position--;
    char **result = {"success", "fail"};
    while(low_position < high_position) {
        int mid_position = (low_position+high_position) >> 1;
        if(a[mid_position] == key) return *result;
        else if(a[mid_position] < key) low_position = mid_position + 1;
        else high_position = mid_position - 1;
    }
    return *(result+1);
}


二分查找函數