13、顺序表查找(顺序表的建立+查找算法)

// 顺序表查找
/*
  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;
}

  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值