Data structure - search (sequential search and binary search)

1. The data structure of the lookup table for sequential search

typedef struct{
	Elemtype *elem;
	int TableLen;         //表的长度 
}SeqList;

2. The main code for sequential search

//一般线性表的顺序查找
int Search_Seq(SSTable ST,ElemType key)
{
	ST.elem[0]=key;        //0号元素放关键字,哨兵
	for(int i=ST.TableLen;ST.elem[i]!=key;i--)
	{
		return i;
	} 
 } 

Its time complexity is O(n); it works for both ordered and linked lists.

3. The data structure of the lookup table for the half lookup

typedef struct{
	Elemtype *elem;
	int TableLen;         //表的长度 
}SSTable;

4. The main code of half search (for ascending order list)

 //折半查找
int Binary_Search(SeqList L,ElemType key)
{
	int low=0,high=L.TableLen-1,mid;
	while(low<=high)
	{
		mid=(low+high)/2;           //取中间位置
		if(L.elem[mid]==key)         //查找成功 
		return mid;
		else if(L.elem[mid]<key)     //在右半边查找 
		{
			low=mid+1;
		} 
		else                           //在左半边查找 
		high=mid-1;
	}
	return -1;
}

Its time complexity is O(logn); but it can only be used for ordered sequential lists, because linked lists do not have the characteristics of random storage. The process of binary search is a balanced binary tree.

If the number of elements between the current Low and high is an odd number, the number of elements on the left and right sides is equal, otherwise the left half is one element less than the right half (for mid=(low+high)/2, that is When it is rounded down, if it is rounded up, it is the opposite).

Guess you like

Origin blog.csdn.net/m0_51769031/article/details/125417475