二分查找算法递归实现

引自Wikipedia 折半搜索算法

//递归版本    
int binary_search( const int arr[], int low, int high, int key)    
{
    
    int mid = low+(high-low)/2;  // Do not use (low+high)/2 which might encounter overflow issue
    
    // not found
    if(low>high)
        return -1;
        
    if(arr[mid]==key)
        return mid;
    else if(arr[mid]>key)
        return binary_search(arr,low,mid-1,key);
   else 
        return binary_search(arr,mid+1,high,key);
}

你可能感兴趣的:(二分查找算法递归实现)