11.静态查找

实验11 静态查找

代码

#include <iostream>
using namespace std;
#define MAXSIZE 100

struct ElemType
{
	int key; //关键字域
	// Other info
};

struct SSTable
{
	ElemType *R;
	int length;
};

// 初始化查找表
void InitSSTable(SSTable &ST)
{
	ST.R = new ElemType[MAXSIZE];
	ST.length = 0;
	if (!ST.R)
	{
		cout << "初始化错误" << endl;
		exit(-1);
	}
}

// 销毁查找表
void DestroySSTable(SSTable &ST)
{
	delete[] ST.R;
}

// 填充查找表
void InsertSSTable(SSTable &ST)
{
	for (int i = 0; i < MAXSIZE; i++)
		ST.R[i].key = i;
	ST.length = MAXSIZE;
}

// 填充查找表, 但是空出0号位置(搜索的时候存储哨兵)
void InsertSSTable2(SSTable &ST)
{
	for (int i = 1; i < MAXSIZE; i++)
		ST.R[i].key = i;
	ST.length = MAXSIZE - 1;
}

// 顺序查找法
int SeqSearch(SSTable &ST, int key)
{
	for (int i = ST.length; i >= 1; --i)
	{
		if (ST.R[i].key == key)
			return i;
	}
	return 0;
}

// 带哨兵的顺序查找
int SeqSearchWithSentry(SSTable &ST, int key)
{
	ST.R[0].key = key; // 设置哨兵
	int i = ST.length;
	while (ST.R[i].key != key)
		i--;
	return i;
}

// 二分查找
int BinarySearch(SSTable &ST, int key)
{
	int low = 1, high = ST.length;
	int mid;
	while (low <= high)
	{
		mid = (low + high) / 2;
		if (key == ST.R[mid].key)
			return mid;
		else if (key < ST.R[mid].key)
			high = mid - 1;
		else
			low = mid + 1;
	}
	return 0; // 没找到
}

// 显示搜索结果
void ShowSearchResult(int result, int testkey)
{
	if (result == 0)
		cout << "未找到" << testkey << endl;
	else
		cout << "找到" << testkey << "位置为" << result << endl;
}

int main()
{
	SSTable ST;
	int testkey1 = 7;
	int testkey2 = 200;

	InitSSTable(ST);
	cout << "-------------------1.顺序查找-------------------" << endl;
	InsertSSTable(ST);
	ShowSearchResult(SeqSearch(ST, testkey1), testkey1);
	ShowSearchResult(SeqSearch(ST, testkey2), testkey2);

	cout << "-------------------2.带监视哨的顺序查找----------" << endl;
	InsertSSTable2(ST); // 0 号位置用作哨兵位
	ShowSearchResult(SeqSearchWithSentry(ST, testkey1), testkey1);
	ShowSearchResult(SeqSearchWithSentry(ST, testkey2), testkey2);

	cout << "-------------------3.折半查找--------------------" << endl;
	InsertSSTable(ST);
	ShowSearchResult(BinarySearch(ST, testkey1), testkey2);
	ShowSearchResult(BinarySearch(ST, testkey2), testkey2);
	
	DestroySSTable(ST);
}

截图

posted @ 2020-12-01 16:43  zaxtyson  阅读(190)  评论(0编辑  收藏  举报