折半查找(递归算法)

#include<stdio.h>
#include<stdlib.h>
int a[1000],k;
int f(int s,int t){
    int m;
    m=(s+t)/2;
    if(a[m]==k)
        return m;
    else if(k>a[m] && m+1<=t)
        return f(m+1,t);
    else if(k<a[m] && s<=m-1)
        return f(s,m-1);
    return -1;
}
int main(){
    int i,j,m,n,ans=-1;
    scanf("%d%d",&n,&k);   
    for(i=1;i<=n;i++)
        scanf("%d",&a[i]);    
    printf("%d\n",f(1,n));
    return 0;    
}

你可能感兴趣的:(C语言,递归算法,基础算法)