初学数据结构---查找代码之静态查找

本文介绍了三种静态查找算法:顺序查找、带有哨兵项的静态查找以及有序数组的折半查找。通过示例代码展示了它们在不同场景下的应用,并在main函数中进行了测试,输出了查找结果。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

#include <iostream>
#include <string>
using namespace std;

const int MAXSIZE = 100;

typedef char KeyType;

typedef struct
{
	KeyType key;
} DataType;

typedef struct
{
	DataType list[MAXSIZE];
	int length;
}SSTable;

//顺序表查找1
int SeqSearch(SSTable S, DataType x)
{
	int i = 0;
	while(i < S.length && S.list[i].key != x.key)
		i++;
	if(S.list[i].key == x.key)
		return i + 1;
	else
		return 0;
}
//哨兵项的静态查找
int SeqSearch2(SSTable S, DataType x)
{
	int i = S.length;
	S.list[0].key = x.key;
	while(S.list[i].key != x.key)
	{
		i--;
	}
	return i;
}

//有序折半查找
int BinarySearch(SSTable S, DataType x)
{
	int low, high, mid;
	low = 0;high = S.length;
	while(low < high)
	{
		mid = (high + low) / 2;
		if(S.list[mid].key == x.key)
			return mid + 1;
		else if(S.list[mid].key < x.key)
		{
			low = mid + 1;
		}
		else high = mid - 1;
	}
	return 0;
}

int main()
{
	SSTable S1 = { {'1','2','3','4','5','6','7','8','9','a','c','d','v','b'},14 };
	SSTable S2 = { { '0','1','2','3','4','5','6','7','8','9'},10 };

	DataType x = { '5'};
	
	int a, b, c, d;

	a = SeqSearch(S1, x);
	cout << "顺序查找:" << a << " " << x.key << endl;
	b = SeqSearch2(S1, x);
	cout << "哨兵项查找:" << b << " " << x.key << endl;
	c = SeqSearch2(S2, x);
	cout << "哨兵项查找:" << c << " " << x.key << endl;
	d = BinarySearch(S2, x);
	cout << "折半查找:" << d << " " << x.key << endl;
	return 0;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值