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
*/
相关推荐
minglie1几秒前
Vitis HLS c转verilog
c语言·开发语言·fpga开发
.简.简.单.单.8 分钟前
Design Patterns In Modern C++ 中文版翻译 第十章 外观模式
c++·设计模式·外观模式
十五年专注C++开发28 分钟前
Jieba库: 一个中文分词领域的经典库
c++·分布式·自然语言处理·中文分词
_OP_CHEN28 分钟前
【C++数据结构进阶】从 Redis 底层到手写实现!跳表(Skiplist)全解析:手把手带你吃透 O (logN) 查找的神级结构!
数据结构·数据库·c++·redis·面试·力扣·跳表
名誉寒冰31 分钟前
Redis 常用数据结构与实战避坑指南
数据结构·数据库·redis
菜菜的院子39 分钟前
vcpkg配置
c++
我的offer在哪里1 小时前
c++的回调函数
开发语言·c++
girl-07261 小时前
2025.12.26代码分析
数据结构·算法
蒙奇D索大1 小时前
【数据结构】排序算法精讲|折半插入排序全解:高效优化、性能对比、实战剖析
数据结构·学习·考研·算法·排序算法·改行学it
Hello eveybody1 小时前
C++四级考试要点
开发语言·c++