顺序查找的实战------c++

系列文章目录

目录

系列文章目录

前言

一、数组的元素的初始化

二、按顺序进行查找

1.代码



前言


一、数组的元素的初始化

#include <iostream>
#include <stdio.h>

#include <stdlib.h>
#include <time.h>

typedef int Element;
typedef struct {//定义结构体类型
    Element *element;//元素指针
    Element Tablen;//元素下标
} STable;

void ST_printf(STable table) {
    for (int j = 1; j < table.Tablen; j++) {
        ;
        printf("%3d",  table.element[j]);
    }//随机生成
}

void ST_init(STable &table, int i) {
    table.Tablen = i + 1;//本次采用的是哨兵模式。所以多加一个元素作为哨兵的存在位置

    table.element = (Element *) malloc(sizeof(Element) * table.Tablen);

    srand(time(NULL));
    for (int j = 1; j < table.Tablen; j++) {
        table.element[j] = rand() % 100;
    }//随机生成数据存入
}

int main() {
    STable sTable;
    ST_init(sTable, 10);
    ST_printf(sTable);
    return 0;
}

 

 

二、按顺序进行查找

1.代码

代码如下(示例):

#include <iostream>
#include <stdio.h>

#include <stdlib.h>
#include <time.h>

typedef int Element;
typedef struct {//定义结构体类型
    Element *element;//元素指针
    Element Tablen;//元素下标
} STable;


void ST_printf(STable table) {
    for (int j = 1; j < table.Tablen; j++) { ;
        printf("%3d", table.element[j]);
    }
}

void ST_init(STable &table, int i) {
    table.Tablen = i + 1;//本次采用的是哨兵模式。所以多加一个元素作为哨兵的存在位置

    table.element = (Element *) malloc(sizeof(Element) * table.Tablen);

    // srand(time(NULL));
    for (int j = 1; j < table.Tablen; j++) {
        int num = j;
        table.element[j] = ++num;
    }//随机生成数据存入
}

int Table_search(STable table, Element key) {
    table.element[0] = key;
    int i;
    for (i = table.Tablen - 1; table.element[i] != key; i--);

    return i;

}

int main() {
    STable sTable;
    ST_init(sTable, 10);
    Element element = 110;
    printf("%d",Table_search(sTable, element));

    // ST_printf(sTable);
    return 0;
}

 

 使用的哨兵进行查找


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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值