折半查找 、顺序查找 、 分块查找 的实现方法
<P><FONT color=#ff0000>下面的链接是源代码,愿意看的点击下载,到C++ 里面运行就是<BR></FONT>[attach]23646[/attach]<BR><BR><BR>以下是源代码<BR>#include "iostream"<BR>#include "math.h"<BR>using namespace std;<BR>#define MAXSIZE 200<BR>typedef int KeyType;<BR>typedef int DataType;<BR>typedef struct <BR>{<BR> KeyType key;<BR> DataType data;<BR>}NodeType;<BR>typedef NodeType SeqList[MAXSIZE];</P><P><BR>void SeqSearch(SeqList S,int n,KeyType k)<BR>{<BR> for(int i=0;i<n&&S[i].key!=k;i++);<BR> if(i<n)<BR> {<BR> cout<<"该数在第 "<<i+1<<" 位"<<endl;<BR> cout<<"顺序查找次数为"<<i<<endl;<BR> }<BR> else <BR> {<BR> cout<<"The number is not exist!SeqSearch has searched "<<i<<" times"<<endl;<BR> }</P>
<P>}</P>
<P>void BinSearch(SeqList S,int n,KeyType k)<BR>{<BR> int low=0,high=n-1,mid,num=0;<BR> while(low<=high)<BR> {<BR> mid=(low+high)/2;<BR> num++;<BR> if(S[mid].key==k)<BR> {<BR> cout<<"折半查找次数为 "<<num<<endl;<BR> exit(0);<BR> }<BR> <BR> else if(S[mid].key<k)<BR> low=mid+1;<BR> else<BR> high=mid-1;<BR> }<BR> cout<<"The number is not exist!BinSearch has searched "<<num<<" times"<<endl;<BR>}</P>
<P>void AreaSearch(SeqList S,int n,KeyType k)<BR>{<BR> int length=sqrt(n);//分块的块长<BR> bool check=false;//查到与否的标志<BR> int b=n%length==0?0:1;<BR> int num=n/length+b;//分的组数<BR> for(int i=0;i<num;i++)<BR> {<BR> int NUM=(i*num+num)<=n?(i*num+num):n;<BR> if(k<S[NUM].key)<BR> {<BR> for(int j=i*num;j<(NUM)&&k!=S[j].key;j++);<BR> if(j<(NUM))<BR> {<BR> cout<<"分块查找次数为 "<<(i+j-i*num+1)<<endl;<BR> check=true;<BR> break;<BR> }<BR> else<BR> {<BR> cout<<"The number is not exist!AreaSearch has searched "<<(i+j-i*num+1)<<" times"<<endl;<BR> check=true;<BR> break;<BR> }<BR> }<BR> else if(k==S[NUM].key)<BR> {<BR> cout<<"分块查找次数为 "<<i+1<<endl;<BR> check=true;<BR> break;<BR> }<BR> }<BR> if(!check)<BR> cout<<"没有找到!分块查找次数为 "<<i+1<<endl;<BR> <BR> <BR>}</P>
<P>void Init(SeqList &Q,int &m,int &n)<BR>{<BR> <BR> while(m>MAXSIZE||m<0)<BR> {<BR> cout<<"请输入数组的长度(不要超过"<<MAXSIZE<<"):";<BR> cin>>m;<BR> }<BR> cout<<endl;<BR> for(unsigned i=0;i<m;i++)<BR> {<BR> Q[i].key=i;<BR> cout<<Q[i].key<<" ";<BR> if((i+1)%10==0)<BR> cout<<endl;<BR> }<BR> cout<<endl<<"请输要查找的数据:";<BR> cin>>n;</P>
<P><BR>}<BR>void main()<BR>{<BR> SeqList Q;<BR> int n;//number you want to find<BR> int m;//length of array<BR> Init(Q,m,n);<BR> SeqSearch(Q,m,n);<BR> AreaSearch(Q,m,n);<BR> BinSearch(Q,m,n);<BR> <BR>}</P> 有长度限制 不是很爽
应该长度动态可以变 才比较好 不知道您使用什么编译
我现在修改了 能在 cfree下
页:
[1]
