〖求助〗折半查找法求助
#include<stdio.h>main()
{
int i,a,x,a;
for(i=0;i<10000;i++)
a=i;
printf("put what you want");
scanf("%d",&x);
if(i>=0&&i<100)k=3;
if(i>=100&&i<1000)k=8;
if(i>=1000&&i<10000)k=14;
for(a=1;a<=k;)
{
if(x==a/k){printf("you want is here a[%d]",i); break;}
if(x<a/k)
if(x>a/k)
}
for(;;)
if(x==)printf("you want is here a[%d]",i);
getch();
}
这是个模型,还没写完,我的基本思路是先判断总的有多少数,决定折半的最高次数,然后用折半查找查找要的数,我一时还写不出来,能有高手帮我吗??? <P>请务必把回复页面左侧的</P><BR>
<P><INPUT type=checkbox value=1 name=atc_convert>Wind Code自动转换</P><BR>
<P>关掉,不然会被自动转换掉,成了斜体标志<BR></P> 折半查找有算法的,要按算法来编程。 折半查找法要用到3个指针,low mid high,low high分别指向查找区间的头和尾,mid=1/2(low+high), 楼主大几的?《数据结构》上过吗? <P>我把折半查找法的算法发上来</P>
<P>int Search_Bin(SSTable ST,KeyType key){</P>
<P>//在有序表ST中折半查找其关键字等于key的数据元素。若找到,则函数值为该元素在表中的位置,否则为0。</P>
<P>low=1; high=ST.length; //置区间初始</P>
<P>while(low<=high){</P>
<P>mid=(low+high)/2;</P>
<P>if(EQ(key,ST.elem.key)) return mid; //找到待查元素</P>
<P>else if(LT(key,ST.elem.key)) high=mid-1; //继续在前半区间进行查找</P>
<P>else low=mid+1; //继续在后半区间进行查找</P>
<P>}</P>
<P>return 0; //顺序表中不存在待查元素</P>
<P>}//Search_Bin</P> 我是大ONE,什么都看不懂啊 <P>查找</P>
<P>看例子比较容易懂</P>
<P><BR>例如:已知11个数据元素的有序表(05,13,19,21,37,56,64,75,80,88,92),现要查找数据元素21和85。</P> <P>#include<stdio.h><BR>main()<BR>{<BR>int key,low,high,mid,a={05,13,19,21,37,56,64,75,80,88,92};<BR>printf("put what you want:");<BR>scanf("%d",&key);<BR>low=0;<BR>high=11;<BR>while(low<=high)<BR>{<BR>mid=(low+high)/2;<BR>if(a==key){printf("you want is here a[%d]",mid);break;}<BR>else if(a>key)high=mid-1;<BR>else low=mid+1;<BR>}<BR>getch();<BR>}<BR></P>
<P>当然这个程序很粗糙了</P> <P>改进了些,但是还是不好。</P>
<P><BR>#define N 11<BR>main()<BR>{<BR>int x,a[]={05,13,19,21,37,56,64,75,80,88,92};<BR>int search(int s,int key);<BR>printf("Put what you want:");<BR>scanf("%d",&x);<BR>if(search(a,x)==0)printf("You want is not here!");<BR>else printf("You want is here a[%d]",search(a,x)-1);<BR>getch();<BR>}</P>
<P>int search(int s,int key)<BR>{<BR>int low=0,high=N,mid;<BR>while(low<=high)<BR>{<BR>mid=(low+high)/2;<BR>if(s==key)return mid+1;<BR>else if(s>key)high=mid-1;<BR>else low=mid+1;<BR>}<BR>return 0;<BR>}</P>
页:
[1]
2