常用查找算法总结

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

 

posted @ 2015-07-12 15:10  Sawyer Ford  阅读(284)  评论(0编辑  收藏  举报