// 顺序表查找
/*
1. 建立顺序表
a.顺序表中存储的数据结构ElemType:key(关键字域)| info(其他数据域)
b.建立顺序表SSTable:ElemType *R(表基) | length(长度)
c.初始化顺序表 (插入些数据)
2.查找
和顺序表中的关键字key对比,
a.相同返回,该关键字存储的位置
b.不同,返回0/-1
优化方法
1 将需要查找的关键字存入s.R[0].key中
2 将查找表0后面的关键字逐一进行比较,返回相同的位置
*/
#include <iostream>
using namespace std;
#define MAXSIZE 100
typedef string KeyType;
// 1. 建立顺序表
// a.顺序表中存储的数据结构ElemType:key(关键字域)| info(其他数据域)
struct ElemType
{
KeyType key; // 关键字域
int info; // 其它域
};
// b.建立顺序表SSTable:ElemType *R(表基) | length(表的长度)
struct SSTable
{
ElemType R[MAXSIZE];
int length;
};
// c.初始化顺序表(插入些数据)
void InitSSTable(SSTable &s);
// 2.查找
int Search_Seq(SSTable &s, const KeyType &k);
int main()
{
SSTable s;
InitSSTable(s);
KeyType k = "czy";
cout << Search_Seq(s, k) << endl;
return 0;
}
// c.初始化顺序表(插入些数据)
void InitSSTable(SSTable &s)
{
s.length = 0;
s.R[1].key = "czy";
s.R[1].info = 100;
s.R[2].key = "wcx";
s.R[2].info = 99;
s.length = 2;
}
// 2.查找
// 简单方法
int Search_Seq1(const SSTable &s, const KeyType &k)
{
// 和顺序表中的关键字key对比,(遍历顺序表)
for (int i = 1; i <= s.length; ++i)
{
if (s.R[i].key == k)
return i;// a.相同返回,该关键字存储的位置
}
return 0;// b.没找到
}
// 优化方法
//1 将需要查找的关键字存入s.R[0].key中
//2 将查找表0后面的关键字逐一进行比较,返回相同的位置
int Search_Seq(SSTable &s, const KeyType &k)
{
s.R[0].key = k;
for (int i = s.length; i > 0; --i)
if(s.R[i].key == k)
return i;
}
13、顺序表查找(顺序表的建立+查找算法)
于 2023-07-07 20:54:55 首次发布