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
*/
相关推荐
汉克老师7 小时前
GESP2024年6月认证C++三级( 第二部分判断题(1-10))
c++·数组·位运算·补码·gesp三级·gesp3级
yuannl108 小时前
数据结构----双端队列实现
数据结构
无限进步_8 小时前
【C++】只出现一次的数字 II:位运算的三种解法深度解析
数据结构·c++·ide·windows·git·算法·leetcode
网域小星球8 小时前
C 语言从 0 入门(十七)|结构体指针 + 动态内存 + 文件综合实战
c语言·开发语言·文件操作·结构体指针·动态内存·综合项目
qq_454245039 小时前
通用引用管理框架
数据结构·架构·c#
小贾要学习9 小时前
【Linux】TCP网络通信编程
linux·服务器·网络·c++·网络协议·tcp/ip
哎嗨人生公众号9 小时前
手写求导公式,让轨迹优化性能飞升,150ms变成9ms
开发语言·c++·算法·机器人·自动驾驶
code_whiter9 小时前
C++6(模板)
开发语言·c++
lcj251110 小时前
【C语言】数据在内存中的存储
c语言·数据结构
一只旭宝10 小时前
【C++ 入门精讲1】初始化、const、引用、内联函数 | 超详细手写笔记(附完整代码)
开发语言·c++