3173. 递归实现二分查找

Naive函数数组递归函数二分查找

时间限制:1000 ms

内存限制:256 MiB

题面

定义一个递归函数 binarySearch,使用二分查找算法查找一个整数在一个数组中的序号(这里计数从 00 开始)。找不到时,返回 1-1

假设数组中的各个元素值均不相同,且已经按升序排序。

//********** Specification of binarySearch **********
int binarySearch (int a[],int L,int R,int x);
/* PreCondition:  
     a is an integer array in ascending order, x is the value to be found
     L and R are lower and upper bounds to be searched
   PostCondition: 
     return position of an element of a that has value x, -1 if not found
*/

请使用提供的主程序测试你的函数,并一起提交。

#include<stdio.h>

#define N 1024

int binarySearch (int a[],int L,int R,int x)
/* PreCondition:  
     a is an integer array in ascending order, x is the value to be found
     L and R are lower and upper bounds to be searched
   PostCondition: 
     return position of an element of a that has value x, -1 if not found
*/
{ //TODO: your function definition
}

int main()
{   int n,i,a[N+1],x;
    scanf("%d",&n);
    for (i=0;i<n;i++) scanf("%d",&a[i]);
    scanf("%d",&x);

//********** binarySearch is called here ***********
    printf("%d\n",binarySearch(a,0,n-1,x));
//*********************************************
    return 0;
}

样例

输入

7
1 3 5 7 53 355 3432
3

输出

1