数据结构_查找
顺序表查找
int sequentialSearch1(int * a, int n, int key)
{
for (int i = 1; i <= n; i++)
{
if (a[i] == key)
{
return i;
}
}
return 0;
}
int sequentialSearch2(int * a, int n, int key)
{
int i = n;
a[0] = key;
while (a[i] != key)
{
i--;
}
return i;
}
注: 哨兵解决了每次比较之后需要判断位置是否越界,提高了效率
有序表查找
int binarySearch(int * a, int n, int key)
{
int low = 1;
int high = n;
int mid = 0;
while (low <= high)
{
mid = low + (high - low) >> 2;
if (a[mid] < key)
{
low = mid + 1;
}
else if (a[mid] > key)
{
high = mid - 1;
}
else
return mid;
}
return 0;
}
插值查找: mid = low + (key- a[low]) / (a[high] - a[low]) * (high - low) 适用于数据比较密集的查找操作
线性索引查找
- 稠密索引
- 分块索引
块内无序,块间有序 (块内使用顺序查找,块间使用二分查找) - 倒排索引
二叉排序树
typedef struct BiTNode
{
int data;
struct BiTNode * lChild;
struct BiTNode * rChild;
}BiTNode, * BiTree;
bool searchBST(BiTree T, int key, BiTree f, BiTree * p)
{
if (!T)
{
*p = f;
return false;
}
else if (key == T->data)
{
*p = T;
return true;
}
else if (key < T->data)
{
return searchBST(T->lChild, key, T, p);
}
else
{
return searchBST(T->rChild, key, T, p);
}
}
bool insertBST(BiTree * T, int key)
{
BiTree p, s;
if (!searchBST(*T, key, NULL, &p))
{
s = (BiTree)malloc(sizeof(BiTNode));
s->data = key;
s->lChild = s->rChild = NULL;
if (!p)
{
*T = s;
}
else if (key < p->data)
{
p->lChild = s;
}
else
{
p->rChild = s;
}
return true;
}
else
return false;
}
bool delF(BiTree * p)
{
BiTree q, s;
if (NULL == (*p)->rChild)
{
q = *p;
*p = (*p)->lChild;
}
else if (NULL == (*p)->lChild)
{
q = *p;
(*p) = (*p)->rChild;
free(q);
}
else
{
q = *p;
s = (*p)->lChild;
while (s->rChild)
{
q = s;
s = s->rChild;
}
(*p)->data = s->data;
if (q != *p)
{
q->rChild = s->lChild;
}
else
{
q->lChild = s->lChild;
}
free(s);
}
return true;
}
bool delR(BiTree * p)
{
BiTree q, s;
if (NULL == (*p)->rChild)
{
q = *p;
*p = (*p)->lChild;
}
else if (NULL == (*p)->lChild)
{
q = *p;
(*p) = (*p)->rChild;
free(q);
}
else
{
q = *p;
s = (*p)->rChild;
while (s->lChild)
{
q = s;
s = s->lChild;
}
(*p)->data = s->data;
if (q != *p)
{
q->lChild = s->rChild;
}
else
{
q->rChild = s->rChild;
}
free(s);
}
return true;
}
bool deleteBST(BiTree * T, int key)
{
if (!*T)
{
return false;
}
else
{
if (key == (*T)->data)
{
return delR(T);
}
else if (key < (*T)->data)
{
deleteBST(&(*T)->lChild, key);
}
else
{
deleteBST(&(*T)->rChild, key);
}
}
}
void InorderBST(BiTree T)
{
if (!T)
{
return;
}
InorderBST(T->lChild);
printf("%d ", T->data);
InorderBST(T->rChild);
}
总结:
- 二叉排序树保留了插入和删除不用移动元素的优点
- 二叉排序树走的就是从根结点到要查找结点的路径
- 二叉排序树的查找性能取决于二叉树的形状,这就有了接下来的二叉平衡树
|