码迷,mamicode.com
首页 > 编程语言 > 详细

常用查找算法总结

时间:2015-07-12 15:31:36      阅读:222      评论:0      收藏:0      [点我收藏+]

标签:

1. 二分查找

技术分享
//递归版
int binarySearch(const int arr[], int low, int high, int val)
{
    if (low <= high)
    {
        int mid = low + (high - low) / 2;    // Do not use (low + high) / 2 which might encounter overflow issue

        if (val < arr[mid])
            return binarySearch(arr, low, mid-1, val);
        else if (val > arr[mid])
            return binarySearch(arr, mid+1, high, val);
        else
            return mid;
    }
    return -1;
}
//非递归版
int binarySearch(const int arr[], int low, int high, int val)
{
    while (low <= high)
    {
        int mid = low + (high - low) / 2;    // Do not use (low + high) / 2 which might encounter overflow issue

        if (val < arr[mid])
            high = mid - 1;
        else if (val > arr[mid])
            low = mid + 1;
        else
            return mid;
    }
    return -1;
}
View Code

 

常用查找算法总结

标签:

原文地址:http://www.cnblogs.com/gattaca/p/4640972.html

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