在日常的算法中,查找是一个经常涉及到的话题,而如何提高查找的速度,也是很多程序员、软件研究的话题。
先看一个例子。
有这样一个数据类型 S :
学生姓名(name),性别(sex),年龄(age)。。。,
现在假设有这样一个需求;
文件A、B中分别存放大量 S 的记录,需要将A、B中重复的记录去掉。
我们用c代码来演示今天的话题:
typedef struct tagSTUDENT
{
char *name ;
bool bSex ;
int age ;
…
} S ;
对于这样一个问题,简单的做法应该是如下:
A 中读取记录,保存到一个链表(指针链表,数组链表都可以)ListA中,B中读取记录,保存到ListB中,然后用两重循环来实现查找:
int i ,j;
int nCountA = ListA.GetCount() ;
int nCountB = ListB.GetCount() ;
for (i=0; i < nCountA ;i++)
{
S *pA = (S*)ListA.GetAt(i) ;
for (j=0; j< nCountB ;j++)
{
S *pB = (S*)ListB.GetAt(j) ;
//比较,匹配
if (strcmp(pA->name, pB->name) == 0)
{
ListA.DeleteAt(i) ;
ListB.DeleteAt(j) ;
i -- ;