使用c实现二分查找,欢迎找茬

P2249 【深基13.例1】查找

leaderpower @ 2024-11-22 16:24:02

#include<stdio.h>
#include<stdlib.h>
int binary_search( int *num,int N,int find)
{
    int begin=0,end=N+1;
    int mid=(begin+end)/2;
    while(begin+1!=end)
    {
        if(num[mid]>=find)
        {
            end=mid;
        }
        else
        {
            begin=mid;
        }
        mid=(begin+end)/2;
    }
    if(num[end]==find)
    {
        return end;
    }
    else
    {
        return -1;
    }
}

int main()
{
 int *num=(int *)malloc(1000001*sizeof(int));
 int N,search,find;
 int i;
 scanf("%d",&N);
 scanf("%d",&search);

 for(i=1;i<=N;i++)
 {
    scanf("%d",&num[i]);
 }
 for(i=1;i<=search;i++)
 {
    scanf("%d",&find);
    printf("%d ",binary_search(num,N,find));
 }

 return 0;  
} 

by XuYueming @ 2024-11-22 16:29:43

@leaderpower orz orz orz orz orz


by An_OIer @ 2024-12-02 21:53:20

呵呵


|