题练(五):二分查找的递归算法和非递归算法

//在递增数组中,非递归算法下的二分查找,若找到目标数字,返回所在数组的下标位置;否则返回-1
int binarySearchByIteration(int arr[], int len, int findData)
{
    if (arr == nullptr || len <= 0)
        return -1;

    int start = 0, end = len - 1, middle = 0;
    while (end >= start)
    {
        middle = start + (end - start) / 2;
        if (arr[middle] == findData)
            return middle;
        else if (arr[middle] < findData)
        {
            start = middle + 1;
        }
        else
        {
            end = middle - 1;
        }
    }
    
    return -1;
}
//递归算法下的二分查找
int binarySearchByRecursion(int arr[], int findData, int start, int end)
{
    if (arr == nullptr || start > end)
        return -1;

    int mid = start + (end - start) / 2;
    if (arr[mid] == findData)
        return mid;
    else if (arr[mid] > findData)
    {
        return binarySearchByRecursion(arr, findData, start, mid - 1);
    }
    else
    {
        return binarySearchByRecursion(arr, findData, mid + 1, end);
    }
}

你可能感兴趣的:(题练(五):二分查找的递归算法和非递归算法)