如何编写二分查找和顺序查找的C语言代码?

2024-11-24 23:59:25
推荐回答(1个)
回答1:

二分查找:
int search(int a[],int x,int n)
{
int mid=0;
int low=0;
int high=n;
while(low<=high)
{
mid=(low+high)/2;
if(a[mid]==x)
{ return mid; }
else if(x { high=mid-1; }
else
{ low=high+1; }
}
return -1;
}
顺序查找:
int search(int a[],int x,int n)
{
int i;
for(i=0;i {
if(a[i]==x)
return i;
else
return -1;
}
}