一、定义
查找表:同一类型的数据元素(或纪录)构成的集合。
经常对查找表进行的操作有:1,查询某个特定的数据元素是否在表中;2,检索某个特定数据元素的各种属性;3,在查找表中插入一个元素;4,在查找表中删去一个元素。
其中前两种是静态查找,后两种是动态查找。
关键字:数据元素(或纪录)中某个数据项的值,用它可以标识一个数据元素(或纪录)。(唯一标识则称为主关键字,否则称次关键字。)
典型的关键字类型可以是整型,实型,字符串型:
typedef float KeyType;
typedef int KeyType;
typedef char *KeyType;
数据元素类型定义为结构体:
typedef struct
{ KeyType key; //关键字域
... //其他域
}SElemType;
二、静态查找表
以顺序表或线性链表表示静态查找表,则search函数可用顺序查找来实现。
静态查找表的顺序储存结构:
typedef struct
{ ElemType *elem; //数据元素存储空间基址,建表时按实际长度分配,0号单元留空
int length; //表长度
}SSTable;
查找函数实现:
#include"malloc.h"
#include"stdio.h" #include"stdlib.h" typedef int ElemType; typedef struct /*静态查找表的顺序存储结构 */ { ElemType *elem; /* 数据元素存储空间基址,建表时按实际长度分配,0号单元留空 */ int length; /* 表长度 */ }SSTable; void Creat_Seq(SSTable &ST,int n) { /* 操作结果: 构造一个含n个数据元素的静态顺序查找表ST(数据来自数组r) */ int i,temp; ST.elem=(ElemType *)malloc((n+1) * sizeof(ElemType)); /* 动态生成n个数据元素空间(0号单元不用) */ if(!(ST).elem) { printf("ERROR\n"); exit(0); } /*内存分配失败结束程序*/ for(i=1;i<=n;i++) { scanf("%d",&temp); *(ST.elem+i)=temp; /* 依次赋值给ST,相当于语句ST.elem[i]=temp;*/ } ST.length=n; } int Search_Seq(SSTable &ST,ElemType key) { /* 在顺序表ST中顺序查找其关键字等于key的数据元素。若找到,则函数值为 */ /* 该元素在表中的位置,否则为0。算法9.1 */ ST.elem[0]=key;
for(i=ST.length;i>=1;i--) //从前往后查找
{ if(ST.elem[i]==key)
return i; //找不到时i为0
}
} main() { SSTable ST; int loc,key; int n; scanf("%d",&n); Creat_Seq(ST,n); //printf("Please input the key value:"); scanf("%d",&key); loc = Search_Seq(ST,key); if(loc!=0) printf("The element position is %d.\n",loc); else printf("The element is not exist.\n"); }
有序表的查找:
以有序表表示静态查找表时,Search函数可用折半查找来实现。
折半查找(二分查找)函数实现:
#include"malloc.h" #include"stdio.h" #include"stdlib.h" typedef int ElemType; typedef struct /*静态查找表的顺序存储结构 */ { ElemType *elem; /* 数据元素存储空间基址,建表时按实际长度分配,0号单元留空 */ int length; /* 表长度 */ }SSTable; void Creat_Seq(SSTable &ST,int n) { /* 操作结果: 构造一个含n个数据元素的静态顺序查找表ST(数据来自数组r) */ int i,temp; ST.elem=(ElemType *)malloc((n+1) * sizeof(ElemType)); /* 动态生成n个数据元素空间(0号单元不用) */ if(!(ST).elem) { printf("ERROR\n"); exit(0); } /*内存分配失败结束程序*/ for(i=1;i<=n;i++) { scanf("%d",&temp); *(ST.elem+i)=temp; /* 依次赋值给ST */ } ST.length=n; } int Search_Seq(SSTable &ST,ElemType key) { /* 在顺序表ST中顺序查找其关键字等于key的数据元素。若找到,则函数值为 */ /* 该元素在表中的位置,否则为0。 */
int low=1,high=ST.length,mid; //标记初始值
while(low<=high)
{ mid=(low+high)/2;
if(ST.elem[mid]==key) //如果很幸运的中间的数据元素就是要查找的,则返回中间值即可
return mid;
else if(ST.elem[mid]>key)
high=mid-1; //如果要查找的值小于有序表的中间值,则继续在前半区间查找
else low=mid+1; //反之则在后半区间查找 } main() { SSTable ST; int loc,key; int n; scanf("%d",&n); Creat_Seq(ST,n); //printf("Please input the key value:"); scanf("%d",&key); loc = Search_Seq(ST,key); if(loc!=0) printf("The element position is %d.\n",loc); else printf("The element is not exist.\n"); }