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
*/
相关推荐
eggwyw10 小时前
C++ union 的一种妙用法
开发语言·c++
ShineWinsu12 小时前
对于Qt:QHBoxLayout常见属性以及方法的解析
c++·qt·面试·gui·客户端·布局管理器·水平布局器
小七在进步13 小时前
string的实现(1)
c++·笔记·visual studio
敲上瘾15 小时前
Qt核心机制:信号与槽详解
开发语言·c++·qt·ui·qt6.3
老花眼猫15 小时前
C语言绘图方法:(10)椭圆缩放旋转
c语言·经验分享·青少年编程·课程设计
牢姐与蒯16 小时前
cpp算法之哈希
c++·算法·哈希算法
lcj251117 小时前
[C++] C++11
开发语言·c++·笔记
小小bugbug21 小时前
带工作窃取的线程池
c++·线程池
南风84112 天前
C++ 四种强制类型转换详解
c++
微笑星河q2 天前
C++STL【vector】常用接口函数使用和迭代器失效问题
开发语言·c++