基本概念
1.查找分为:动态查找【在查找的同时对表做修改运算(如插入和删除)】、静态查找
2.由于查找运算的主要运算是关键字的比较,所以通常把查找过程中对关键字执行的平均比较次数(也称为平均查找长度)作为衡量一个查找算法效率优劣的标准。平均查找长度ASL(Average Search Length)定义为:
A
S
L
=
∑
i
=
1
n
p
i
c
i
ASL=\sum_{i=1}^np_ic_i
ASL=i=1∑npici
其中,n是查找表中元素的个数。pi是查找第i(1≤i≤n)个元素的概率,一般地,除特别指出外,均认为每个元素的查找概率相等,即pi=1/n,ci是找到第i个元素所需进行的比较次数。
3.
3.
3.
静态查找表
顺序查找
采用顺序表。又称线性查找
A
S
L
u
n
s
u
c
c
=
n
ASL_{unsucc}=n
ASLunsucc=n
typedef struct
{
int key[maxsize];
int data[maxsize];
}SqType;
int SqSearch(SqType R, int n, int k)
{
int i = 0;
while (i < n && R.key[i] != k)
{
i++;
}
if (i >= n)
return 0;
else
return R.data[i];
}
折半查找
实例:
int ListSearch(sqlist l,int k)
{
int low = 0, high = l.length - 1, mid;
while (low <= high)
{
mid = (low + high) / 2;
if (l.data[mid] == k)
return mid + 1;
else if (l.data[mid] > k)
high = mid - 1;
else
low = mid + 1;
}
return 0;
}
索引查找
2.分块
动态查找表
二叉排序树
typedef struct ElemType
{
int key;
};
typedef struct bitnode
{
ElemType data;
struct bitnode *lchild, *rchild;
}*bitree;
void InsertTree(bitree *t, int x)
{
bitree s;
if (*t == NULL)
{
s = new bitnode;
s->data.key = x;
s->lchild = s->rchild = NULL;
*t = s;
}
else
{
if ((*t)->data.key > x)
InsertTree(&((*t)->lchild), x);
else if((*t)->data.key < x)
InsertTree(&((*t)->rchild), x);
}
}
bitree CreateTree()
{
int x;
bitree t = NULL;
cin >> x;
while (x != -1)
{
InsertTree(&t, x);
cin >> x;
}
return t;
}
bitree SearchTree(bitree t, int x)
{
while (t)
{
if (t->data.key == x)
return t;
else
if (t->data.key > x)
return SearchTree(t->lchild, x);
else
return SearchTree(t->rchild, x);
}
return NULL;
}
void OutputTree(bitree t)
{
if (t != NULL)
{
OutputTree(t->lchild);
cout << t->data.key << " ";
OutputTree(t->rchild);
}
else return;
}
void main()
{
bitree t, p;
int x;
cout << "输入需要查找的数组:" << endl;
t = CreateTree();
cout << "排序后数组:" << endl;
OutputTree(t);
cout << "\n输入要查找元素:" << endl;
int k;
cin >> k;
p = SearchTree(t, k);
if (p != NULL)
cout << "该元素存在:" << p->data.key << endl;
else
cout << "不存在" << endl;
}