一、查找
参考书:《数据结构(C语言)》–严蔚敏等编著,清华大学出版社。
1、顺序表的查找
查找的定义很简单,查找到则称为是成功的,查找不到则称为是不成功的,在查找的实际应用中,引入了两种查找表:静态查找表和动态查找表;
静态查找表:(1)查询某个 “特定的” 数据元素是否存在于表中,(2)检索某个 “特定的” 数据元素的各种属性;
动态查找表:(1)若在查找过程中同时进行插入查找表中不存在的数据元素,或者从查找表中删除已存在的某个数据元素;
所查找的特定的数据元素称为关键字key
;
在定义数据元素类型方面:
typedef int KeyType;
typedef struct {
KeyType key; //关键字域
}ElemType;
typedef struct {
ElemType *elem; //存储空间基址(定义了一个静态存放数据的数组)
int length; //表长
}STTable;
顺序表的查找的应用范围:(1)顺序表或链表表示的静态查找表;(2)表内元素无序;
2、平均查找长度ASL
平均查找长度是评价查找算法的指标:关键字的平均比较次数 => 平均查找长度
;
A
S
L
=
∑
i
=
1
n
p
i
c
i
ASL ={\color{red} \sum_{i=1}^{n} pi ci}
ASL=i=1∑npici
n = 记录的个数;
pi = 查找第i个记录的概率;
ci = 找到第i个记录所需要的比较次数;
时间复杂度:O(n)
;;空间复杂度:O(1)
;
顺序表的查找优缺点:
优点:算法简单,逻辑次序无要求,且不同存储结构均使用;
缺点:ASL太长,时间效率太低;
相关代码:
#include "stdio.h"
#include "stdlib.h"
#define OK 1
#define ERROR 0
#define MAXSIZE 100
typedef int Status;
typedef int KeyType;
typedef struct {
KeyType key; //定义关键字域
} ElemType;
typedef struct {
ElemType *elem; //存储空间基址(定义了一个静态存放数据的数组)
int length; //表长
} STTable;
Status InitTable(STTable &ST,int n);
Status InitTable(STTable &ST,int n) {
ST.elem = (ElemType *)malloc(MAXSIZE*sizeof(ElemType));
if(!ST.elem) return ERROR;
ST.length = 0;
int i,num;
for(i=1; i<=n; i++) { //0号单元备用
scanf("%d",&num);
ST.elem[i].key = num;
ST.length++;
}
return OK;
}
Status Search_Seq(STTable ST,KeyType key);
//在顺序表ST中查找值为key的数据元素(从后往前找)
Status Search_Seq(STTable ST,KeyType key) {
ST.elem[0].key = key; //哨兵
int i;
for(i=ST.length; ST.elem[i].key != key; --i);
return i;
/*
for(int i=ST.length; i>=1; --i) //后往前
if(ST.elem[i].key == key) return i;
return 0;
*/
/*
for(int i=1; i<=ST.length; i++) //前往后
if(ST.elem[i].key == key) return i;
return 0;
*/
}
int main(void) {
STTable ST;
int n,key,i;
scanf("%d",&n);
InitTable(ST,n);
scanf("%d",&key);
i = Search_Seq(ST,key);
if(i != 0) printf("%d\n",i);
else printf("查无此项\n");
return 0;
}
/*
输入:
5
12 33 15 10 8
20
输出:查无此项
输入:
6
12 33 15 10 8 77
12
输出:1 //位置
*/