分塊查找C++

#include <bits/stdc++.h>

using namespace std;

struct index
{
	int key;
	int start;

} newIndex[3];
int search(int key, int* a)
{
	int i = 0, startValue = newIndex[i].start;
	while (i<3 && key>newIndex[i].key)i++;
	if (i >= 3)	return -1;
	while (startValue <= startValue + 5 && a[startValue] != key)startValue++;
	if (startValue > startValue + 5)return -1;
	return startValue;
}
int cmp(const void* a, const void* b)
{
	return (*(struct index*)a).key > (*(struct index*)b).key ? 1 : -1;
}
int main(void)
{
	int a[] = { 33,42,44,38,24,48, 22,12,13,8,9,20, 60,58,74,49,86,53 }, j = -1, key;
	for (int i = 0; i < 3; i++)
	{
		newIndex[i].start = j + 1;
		j += 6;
		for (int k = newIndex[i].start; k <= j; k++)if (newIndex[i].key < a[k])newIndex[i].key = a[k];
	}
	qsort(newIndex, 3, sizeof(newIndex[0]), cmp);
	cin >> key;
	cout << search(key, a);;
}

思路:
分塊查找,也叫索引順序查找,算法實現除了需要查找表本身之外,還需要根據查找表建立一個索引表。例如圖 1,給定一個查找表,其對應的索引表如圖所示:
在這裏插入圖片描述
以圖 1 中的查找表爲例,假設要查找關鍵字 38 的具體位置。首先將 38 依次和索引表中各最大關鍵字進行比較,因爲 22 < 38 < 48,所以可以確定 38 如果存在,肯定在第二個子表中。

由於索引表中顯示第二子表的起始位置在查找表的第 7 的位置上,所以從該位置開始進行順序查找,一直查找到該子表最後一個關鍵字(一般將查找表進行等分,具體子表個數根據實際情況而定)。結果在第 10 的位置上確定該關鍵字即爲所找。

提示:在第一步確定塊(子表)時,由於索引表中按照關鍵字有序,所有可以採用折半查找算法。而在第二步中,由於各子表中關鍵字沒有嚴格要求有序,所以只能採用順序查找的方式。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章