顺序查找
#include
#define N 10
int search_sort(int *a,int keys);
int main(int argc,char argv[])
{
int a[N]={1,2,3,4,5,6,7,8,9,10};
int key;
int s;
scanf("%d",&key);
s=search_sort(a,key);
if(s!=-1)
{
printf("%d ",s);
}
else
{
perror("error\n");
}
return 0;
}
int search_sort(int *a,int keys)
{
int i;
for(i=0;i
折半查找
#include
#define N 11
int search_sort(int *a,int keys);
int main(int argc,char argv[])
{
int a[N];
int key;
int s,i;
for(i=1;ia[tmp])
{
left=tmp+1;
}
else
{
right=tmp-1;
}
}
return -1;
}
分块查找
#include
//块查找的弊端不是整数个的话可能不能查找
struct list{
int date;
int start;
int end;
}s[3];
int sort(int *ss,int key);
int main(int argc,char *argv[])
{
int i,j=0,key,s1;
int a[10];
for(i=1;i<=9;i++)
{
scanf("%d",&a[i]);
}
//进行分块
for(i=0;i<3;i++)
{
s[i].start=j+1;
j=j+1;
s[i].end=j+2;
j=j+2;
s[i].date=a[j];
}
printf("please input a number:");
scanf("%d",&key);
s1=sort(a,key);
if(s1!=0)
{
printf("%d",s1);
}
else
{
perror("error");
}
return 0;
}
#include
//块查找的弊端不是整数个的话可能不能查找
struct list{
int date;
int start;
int end;
}s[3];
int sort(int *ss,int key);
int main(int argc,char *argv[])
{
int i,j=0,key,s1;
int a[10];
for(i=1;i<=9;i++)
{
scanf("%d",&a[i]);
}
//进行分块
for(i=0;i<3;i++)
{
s[i].start=j+1;
j=j+1;
s[i].end=j+2;
j=j+2;
s[i].date=a[j];
}
printf("please input a number:");
scanf("%d",&key);
s1=sort(a,key);
if(s1!=0)
{
printf("%d",s1);
}
else
{
perror("error");
}
return 0;
}
int sort(int *ss,int key)
{
int i=0,j;
while(i<3&&key>s[i].date)
{
i++;
}
if(i>=3)
{
return -1;
}
j=s[i].start;
while(j<=s[i].end&&ss[j]!=key)//进行遍历
{
j++;
}
if(j>s[i].end)
{
return -1;
}
else
{
return ss[j];
}
}