查找是数据处理中使用频繁的一种操作,当数据量较大时,提高各种查找算法的效率就显得十分重要。
此文以学习C语言(基础)为出发点,同时学习数据处理的一些算法。
1 顺序查找
算法思想:从数组的第一份元素开始,将给定的值逐个与数组中的数比较,直到都两者相等。
代码:
#include <stdio.h>
void search(int key,int a[],int n) /*自定义search()函数,实现数序查找**/
{
int i,count=0, count1=0;
for(i=0;i<n;i++)
{
count++; /*count记录查找次数*/
if(a[i]==key)/*判断要查找的关键字与数组中的元素是否相等*/
{
printf("search %d times a[%d]=%d\n",count,i,key);/*打印查找次数及在数组中的位置*/
count1++;/*count1记录查找正确的次数**/
}
}
if (count1==0)/*判断是否查找到**/
{
printf("no found!");
}
}
void main()
{
int n,key,a[100],i;
printf("please input the length of array:\n");
scanf("%d",&n);/*把输入的值存在变量n中,n为数组a的元素个数**/
printf("please input element:\n");
for (i=0;i<n;i++)
{
scanf("%d",&a[i]);/*把输入的值存在变量a[i]中,a[i]为数组a的元素**/
}
printf("please input the number which do you want to saerch:\n");
scanf("%d",&key);
search(key,a,n);
}
执行结果:
2 二分查找
算法思想:首先选取表中的中间位置的记录,将其关键字与给定的关键字key比较,若相等,则查找成功;若key值比关键字大,则要找的元素在右子表中,继续折半查找;若key值比关键字小,则要找的元素在左子表中,继续对左子表折半查找。如此递推,直到查找成功或失败。
缺点:数组元素需按从小到大的顺序排列,通过实验严谨性并不强,后续改进。
代码:
#include<stdio.h>
/*自定义二分查找函数*/
void search(int key,int a[],int n)
{
int low,high,mid,count=0,count1=0;
low=0;
high=n-1;
while(low<high)
{
count++;/*记录查找次数*/
mid=(low+high)/2;/*求出中间位置*/
if(key<a[mid])/*当key小于中间值*/
{
high=mid-1;/*确定左子表范围*/
}
else if(key>a[mid])/*当key大于中间值*/
{
low=mid+1;/*确定右子表范围*/
}
else if(key==a[mid])/*当key等于中间值,查找成功*/
{
printf("success!\nsearch %d times! a[%d]=%d",count,mid,key);
count1++;/*记录查找成功次数*/
break;
}
}
/*判断是否查找失败*/
if (count1==0)
{
printf("no found!\n");
}
}
void main()
{
int i,key,a[100],n;
printf("please input the length of array:\n");
scanf("%d",&n);
printf("please input the element:\n");
for (i=0;i<n;i++)
{
scanf("%d",&a[i]);
}
printf("please input the number which do you want to search:\n");
scanf("%d",&key);
search(key,a,n);
}
执行结果: