C/C++: 数据结构之索引查找(分块查找)

画图举例:

cpp 复制代码
#include<bits/stdc++.h>
using namespace std;
/**
*
* Author:HackerHao
* Create:2023.12.14
*
*/
typedef struct
{
	int Key;
	int Link;
}indextype;

//分块查找
int IndexSequelSearch(indextype ls[], int s[], int m, int Key)
//关键字为Key, 索引表为ls[0]--ls[m-1], 顺序表为s, 块长为l,m为顺序表长度
{
	int i = 0, j = 0;

	//在索引表中顺序查找
	while (i < m && Key > ls[i].Key)
		i++;

	if (i >= m)
		return -1;      //说明没找到,已经越界,返回-1

	else
	{
		//在顺序表中顺序查找

		j = ls[i].Link;
		while (Key != s[j] && j - ls[i].Link < m + 1)
			j++;                //还没有找到

		if (Key == s[j])
			return j;          //找到
		else
			return -1;
	}
}
int main()
{
	cout << "请输入索引表的块数" << endl;
	int n;
	cin >> n;
	indextype ls[n];
	cout << "请输入每一块中最大的元素和每块的分隔处元素下标: " << endl;

	for (int i = 0; i < n; i++)
	{
		cin >> ls[i].Key >> ls[i].Link;
	}
	cout << "请输入顺序表的元素个数、各自的值:" << endl;

	int cnt = 0;
	cin >> cnt;				 //顺序表元素个数
	int SqList[cnt];
	for (int i = 0; i < cnt; i++)
		cin >> SqList[i];    //各元素值

	int key, m = n;
	cout << "请输入想要查找到元素:" << endl;
	cin >> key;

	int u;
	u = IndexSequelSearch(ls, SqList, m, key);

	if (u != -1)
		cout << "查找成功,为第" << u + 1 << "个记录" << endl;
	else
		cout << "查找失败,不存在!" << endl;

	return 0;
}

/* 输入:
4

14 0
34 5
66 10
85 15

20
8 14 6 9 10 22 34 18 19 31 40 38 54 66 46 71 78 68 80 85
*/
相关推荐
爱吃喵的鲤鱼11 分钟前
仿mudou——Connection模块(连接管理)
linux·运维·服务器·开发语言·网络·c++
郝学胜-神的一滴44 分钟前
使用Linux的read和write系统函数操作文件
linux·服务器·开发语言·数据库·c++·程序人生·软件工程
奔跑吧邓邓子1 小时前
【C语言实战(6)】解锁C语言循环密码:for循环实战探秘
c语言·实战·for循环
GilgameshJSS1 小时前
STM32H743-ARM例程15-RTC
c语言·arm开发·stm32·实时音视频
2301_803554521 小时前
C++联合体(Union)详解:与结构体的区别、联系与深度解析
java·c++·算法
pu_taoc1 小时前
深入剖析:基于epoll与主从Reactor模型的高性能服务器设计与实现
服务器·c语言·c++·vscode
初圣魔门首席弟子1 小时前
c++ bug 函数定义和声明不一致导致出bug
开发语言·c++·bug
bkspiderx2 小时前
C++设计模式之行为型模式:中介者模式(Mediator)
c++·设计模式·中介者模式
敢敢J的憨憨L3 小时前
GPTL(General Purpose Timing Library)使用教程
java·服务器·前端·c++·轻量级计时工具库
小欣加油3 小时前
leetcode 62 不同路径
c++·算法·leetcode·职场和发展