C语言的二分查找 10

#include<stdio.h>#include<stdlib.h>intsearch(int*a,intkey){intlow=0;inthigh=14;intmid... #include <stdio.h>
#include <stdlib.h>

int search(int *a,int key)
{
int low=0;
int high=14;
int mid;
while(low<=high)
{
mid=(low+high)/2;
if(key==a[mid])
return mid;
else if(key<a[mid])
high=mid-1;
else
low=mid+1;}
return 0;
}

int main()
{
int *a,key,i=0;
int b[15]={0};
a=b;
printf("please input all the 15 data(from small to big) \n ");
for(i=0;i<15;i++)
{scanf("&d",&b[i-1]);
printf("\n");}
printf("please input the key");
scanf("%d",&key);
if(!search(a,key))
printf("there is no data you are searching for \n");
printf("the data you are searching for is in the %dth place\n",search(a,key));
getchar();
}

怎么改
展开
 我来答
whiledoing
2010-12-16 · TA获得超过171个赞
知道小有建树答主
回答量:103
采纳率:0%
帮助的人:78万
展开全部
#include <stdio.h>
#include <stdlib.h>

int search(int* a, int key)
{
int low = 0;
int high = 14;
int mid;
while (low <= high)
{
mid = (low + high) / 2;
if (key == a[mid])
return mid;
else if (key < a[mid])
high = mid - 1;
else
low = mid + 1;
}
return 0;
}

int main()
{
int* a, key, i = 0;
int b[15] =
{
0
};
a = b;
printf("please input all the 15 data(from small to big) \n ");
for (i = 0; i < 15; i++)
{
scanf("&d", &b[i]); //这里是b[i]
printf("\n");
}
printf("please input the key");
scanf("%d", &key);
if (!search(a, key))
printf("there is no data you are searching for \n");
else //这个else不能少,不然你怎么运行都会输出下面的语句
{
printf("the data you are searching for is in the %dth place\n",
search(a, key));
}
getchar();
return 0;
}
Z雨泽
2010-12-20
知道答主
回答量:4
采纳率:0%
帮助的人:4887
展开全部
编译环境VS2010
适合初学者。
以下是代码:

#include "stdafx.h"

int _tmain(int argc, _TCHAR* argv[])
{
int search(int x,int b[],int c);
int a[10]={0,1,2,3,4,5,6,7,8,9};
int n;
printf("please input a number:\n");
scanf("%d",&n);
printf("the result is:\n");
if(search(n,a,10)>0)
{
printf("the number is found in %d.\n",search(n,a,10));
}
else
printf("the number is not found.\n");

return 0;
}

int search(int x,int b[],int c)
{
int min,mid,max,i,m;
min=0;max=c;

if(x>c-1||x<0)
m=-1;
else
{
for(i=0;i<c-1;i++)
{
mid=(min+max)/2;
if(x==mid)
{
m=mid;
break;
}
else if(x<mid)
max=mid;
else
min=mid;
}
}

return(m);
}
已赞过 已踩过<
你对这个回答的评价是?
评论 收起
推荐律师服务: 若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询

为你推荐:

下载百度知道APP,抢鲜体验
使用百度知道APP,立即抢鲜体验。你的手机镜头里或许有别人想知道的答案。
扫描二维码下载
×

类别

我们会通过消息、邮箱等方式尽快将举报结果通知您。

说明

0/200

提交
取消

辅 助

模 式