使用c实现二分查找,欢迎找茬
查看原帖
使用c实现二分查找,欢迎找茬
1590234
leaderpower楼主2024/11/22 16:24
#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;	
} 
2024/11/22 16:24
加载中...