码迷,mamicode.com
首页 > 其他好文 > 详细

二分查找函數

时间:2014-10-25 23:04:40      阅读:155      评论:0      收藏:0      [点我收藏+]

标签:二分查找

找到,返回下標;

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);
}


二分查找函數

标签:二分查找

原文地址:http://blog.csdn.net/keshacookie/article/details/40457643

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!