Linear Table Lookup - Lookup Table


Linear table storage structure

//数据类型
typedef struct
{
    
    
	int key;
	int other;
}ElemType;
//关键字类型
typedef int KeyType;
typedef struct
{
    
    
	ElemType* elem;//数组基地址
	int length;//表长度
	int size;//表的容量
}SSTable;

1. Sequential search O(n)

search one by one

int SeqSearch1(const SSTable* st, KeyType k)
{
    
    
	assert(st);
	//数据元素从1号单元开始存放,0号单元留空
	for (int i = st->length; i >= 1; i--)//存在条件判断,效率不佳
		if (EQ(st->elem[i].key, k))return i;
}

Improvements for removing conditional judgments

int SeqSearch2(const SSTable* st, KeyType k)
{
    
    
	assert(st);
	//在表st中查找关键字为k的记录,若找到,返回记录在数组中的下标,否则返回0
	st->elem[0].key = k;//存放监视哨
	int i = 0;
	for (i = st->length; !EQ(st->elem[i].key, k); i--)//从表尾端开始向前查找
		return i;
}

2. Binary search O(logn)

Perform a binary search on an ordered sequence

//二分查找
int BiSearch1(const SSTable* st, KeyType k)//非递归
{
    
    
	//用二分法在查找表st中查找关键字值为k的记录,若找到则返回在数组中的下标,否则返回为0
	int left = 1, right = st->length;
	while (left <= right)
	{
    
    
		int mid = (left + right) / 2;
		if (EQ(st->elem[mid].key, k))return mid;//查找成功
		else if (LT(st->elem[mid].key, k))left = mid + 1;//右半区间
		else right = mid - 1;//左半区间
	}
	return 0;//查找失败
}
int BiSearch2(const SSTable* st, KeyType k,int left ,int right)//递归
{
    
    
	if (left > right)return -1;
	else
	{
    
    
		int mid = (left + right) / 2;
		if (EQ(st->elem[mid].key, k))return mid;//查找成功
		else if (LT(st->elem[mid].key, k))return BiSearch2(st, k, mid + 1, right);//右半区间
		else return BiSearch2(st, k, left, mid - 1);//左半区间
	}
}

Disadvantages: It needs to be ordered, and the sorting takes a long time; it is not convenient to insert data.

3. Block search

Divide the sequence into several intervals, the keywords of the intervals are ordered in a certain order, and the data in the block does not need to be ordered.
The so-called quick sequence means that the key values ​​of all records in each block are greater (ascending) or less than (descending) the values ​​of all keys in the previous block. The data elements of the index table respectively record the maximum key and the starting address of each block.
When searching for a keyword, first determine which interval to search for, find a certain block, and search for the keyword sequentially in the block.

Guess you like

Origin blog.csdn.net/zxj20041003/article/details/130019996
Recommended