顺序查找的基本思想是:从表的一端开始,顺序扫描线性表,依次将扫描到的记录与给定值key比较,若相同,则扫描成功;若扫描结束后,仍然未找到与k相等的记录,则扫描失败。
#include "stdio.h"
#define MAX 10
int SeqSearch(int s[],int n,int key)
{
int i;
for(i=0;i<10&&s[i]!=key;i++);
if(i>=10)
return -1;
else
return i;
}
void main()
{
int i,key;
int a;
int arry[MAX];
printf("Input the data:");
for(i=0;i<MAX;i++)
{
scanf("%d",&arry[i]);
}
printf("Input the key: ");
scanf("%d",&key);
a=SeqSearch(arry,10,key) ;
printf("the key is %d it's position is %d.",key,a);
getch();
}
运行结果如下所示:
Input the data:0 1 2 3 4 5 6 7 8 9
Input the key:9
the key is 9 it's position is 9.
二分查找的基本思想是:首先将给定的值key与表中中间位置的记录相比较,若二者相符,则查找成功;否则根据比较的结果确定下次查找的范围,然后在新的查找范围中进行查找,如此重复下去。
#include "stdio.h"
#define MAX 10
int BinSearch(int s[],int n,int key)
{
int low=0;
int high=n-1;
int mid;
while(low<high)
{
mid=(low+high)/2;
if(s[mid]==key)
return mid;
if(s[mid]>key)
high=mid-1;
else
low=mid+1;
}
return -1;
}
void main()
{
int i,key;
int a;
int arry[MAX];
printf("Input the data:");
for(i=0;i<MAX;i++)
{
scanf("%d",&arry[i]);
}
printf("Input the key ");
scanf("%d",&key);
a=BinSearch(arry,10,key) ;
printf("the key is %d it's position is %d:",key,a);
getch();
}
运行结果如下所示:
Input the data:0 1 2 3 4 5 6 7 8 9
Input the key:5
the key is 5 it's position is 5.