分块查找

#include <iostream>
#include <malloc.h>

using namespace std;

#define MAXL 100
#define MAXI 20
typedef int KeyType;
typedef char InfoType;

typedef struct {
	KeyType key;//关键字
	InfoType data;//其他数据项
}RecType;

typedef struct {
	KeyType key;
	int link;//指向分块的起始下标
}IdxType;

void CreateList(RecType R[], KeyType keys[], int n) {//创建顺序表
	for (int i = 0; i < n; i++) {
		R[i].key = keys[i];
	}
}

void DispList(RecType R[], int n) {//输出顺序表
	for (int i = 0; i < n; i++) {
		cout << R[i].key << " ";
	}
	cout << endl;
}

int IdexSearch(IdxType I[], int b, RecType R[], int n, KeyType k) {//分块查找
	int s = (n + b - 1) / b;
	int count1 = 0, count2 = 0;
	int low = 0, high = b - 1, mid, i;
	cout << "(1)在索引表中折半查找:" << endl;
	while (low <= high) {
		mid = (low + high) / 2;
		printf("第%d次比较:在[%d,%d]中比较元素R[%d]:%d\n", count1 + 1, low, high, mid, R[mid].key);
		if (I[mid].key >= k) {
			high = mid - 1;
		}
		else {
			low = mid + 1;
		}
		count1++;
	}
	printf("比较%d次,在第%d块中查找元素%d\n", count1, low, k);
	i = I[high + 1].link;
	cout << "(2)在顺序表中查找元素:" << endl;
	while (i <= I[high + 1].link + s - 1) {
		cout << R[i].key<<" ";
		count2++;
		if (R[i].key == k)
			break;
		i++;
	}
	printf("比较%d次,在顺序表中查找元素%d\n", count2, k);
	if (i <= I[high + 1].link + s - 1) {
		return i + 1;
	}
	else
		return 0;
}

int main() {
	RecType R[MAXL];
	IdxType I[MAXI];
	int n = 25, i;
	int a[] = { 8,14,6,9,10,22,34,18,19,31,40,38,54,66,46,71,78,68,80,85,100,94,88,96,87 };
	CreateList(R, a, n);

	//建立索引表
	I[0].key = 14; I[0].link = 0;
	I[1].key = 34; I[1].link = 4;
	I[2].key = 66; I[2].link = 10;
	I[3].key = 85; I[3].link = 15;
	I[4].key = 100; I[4].link = 20;

	cout << "关键字序列:" << endl;
	for (i = 0; i < n; i++) {
		printf("%4d", R[i].key);
		if (((i + 1) % 5) == 0)
			cout << " ";
		if (((i + 1) % 10) == 0)
			cout << endl;
	}
	cout << endl;

	KeyType k = 46;
	cout << "查找" << k << "的比较过程如下:" << endl;

	if ((i = IdexSearch(I, 5, R, 25, k)) != -1)
		cout << "元素" << k << "的位置是:" << i << endl;
	else
		cout << "元素" << k << "不在表中" << endl;
	return 1;
}

在这里插入图片描述

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值