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

#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; //说明没找到,已经越界,返回-1else{//在顺序表中顺序查找j = ls[i].Link;while (Key != s[j] && j - ls[i].Link < m + 1)j++; //还没有找到if (Key == s[j])return j; //找到elsereturn -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;elsecout << "查找失败,不存在!" << endl;return 0;
}/* 输入:
414 0
34 5
66 10
85 1520
8 14 6 9 10 22 34 18 19 31 40 38 54 66 46 71 78 68 80 85
*/