Linear table lookup of C language algorithm

1. Find related concepts

This section explains the basic concepts related to searching in the data structure:

  • Find: The process of finding data elements that meet certain conditions in a data set.
  • Lookup table: a collection of data used for lookups
  • Keyword: The value of a data item in a data element that uniquely identifies the element
  • Static lookup table: The static lookup table means that after the lookup table is established, the elements in the lookup table will not change.
  • Dynamic lookup table: The dynamic lookup table means that after the lookup table is established, the elements in the lookup table may change such as addition and deletion.
  • Search length: The search length refers to the number of keywords that need to be compared when performing a search operation
  • Average search length: The average search length refers to the result of dividing the sum of all search lengths by n when performing n search operations.

2. Sequential search (linear search)

1. Object

  • static lookup table
  • Linear list (sequence list, linked list)

2. Principle

Starting at the beginning of the data structure, each element is examined in turn until the target element is found or the end of the data structure is reached.

Specific steps are as follows:

  1. Start traversing from the first element of the data structure, and compare with the target element in turn.
  2. Returns the element position if the current element is equal to the target element.
  3. If the target element is not found after traversing all the elements (that is, reaching the end of the data structure), return search failure.

The time complexity of sequential lookup is O(n), where n is the number of elements in the data structure. Sequential search is a commonly used search method when the amount of data is small or the data structure does not have a specific ordered nature.

3. Code

typedef struct{
    
                            //查找表的数据结构(顺序表)
ElemType *elem;                        //动态数组基址
int TableLen;                           //表的长度
}SSTable;

//顺序查找
int Search_ _Seq(SSTable ST, ElemType key){
    
    
	int i;
	for( i=0;i<ST. TableLen)&& ST.elem[i] !=key; ++i);        //查找成功,则返回元素下标;查找失败,则返回-1
	return i==ST.TableLen? (-1): i;
}

3. Half search (binary search)

1. Object

  • static lookup table
  • ordered sequence list

2. Principle

Its principle is based on the following ideas:

  1. First determine the left and right endpoints mid, left and right of the interval to be searched, and calculate the middle position mid.
  2. Compares the value to be found with the element at position mid. If they are equal, return mid; otherwise, judge the relationship between the search value and the size of the mid element, if it is smaller than the element at the mid position, continue searching in the left interval; otherwise, continue searching in the right interval.
  3. Repeat the above operations until the target element is found or the interval is empty.

Specifically, the implementation steps of binary search are as follows:

  1. Initialize left and right as the left and right endpoints of the array, that is, left=0, right=n-1, where n represents the length of the array.
  2. Calculate the mid position, ie mid = (left + right) / 2.
  3. Determine whether the lookup value is equal to the element at the mid position, and if so, return mid. If not, compare the search value with the size relationship of the element at the mid position, if it is smaller than the element at the mid position, continue to search in the interval from left to mid - 1; otherwise, continue to search in the interval from mid + 1 to right .
  4. Repeat steps 2 and 3 until the target element is found or the interval is empty.

It should be noted that the binary search is only applicable to ordered arrays. If the array is not sorted, you need to sort the array first.

The time complexity of binary search (binary search) is O(log n).

3. Code

typedef struct{
    
                            //查找表的数据结构(顺序表)
ElemType *elem;                        //动态数组基址
int TableLen;                           //表的长度
}SSTable;

//折半查找
int Binary_ Search(SSTable 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)
			high=mid-1;             //从前半部分继续查找
		else
			low=mid+1;              //从后半部分继续查找
	}
	return - 1;                     //查找失败,返回-1 
}

Four. Block search (index order search)

1. thought

Its basic idea is to divide the ordered table into several blocks, store multiple keywords in each block, and connect the blocks in order of the size of the keywords. This forms a "blockchain".

When performing a search, a binary search is performed in the block first, and if the keyword is found, it is returned; if not found, it is necessary to continue searching in adjacent blocks. Since the blocks are ordered, a method similar to binary search can be used to determine which block needs to be entered for search, thereby reducing the number of search times and improving search efficiency.

The time complexity of block search is O(√n), where n represents the number of elements in the ordered list. Although its efficiency is not as good as binary search, in some specific cases, such as fewer search times and larger tables, block search still has certain advantages.

2. C language simulation block search

int blockSearch(int arr[], int n, int x, int blockSize) {
    
    
    // 计算块数
    int blocks = (int)ceil((double)n / blockSize);
    // 数组 index 表示每个块的起始下标,maxIndex 表示当前块中最大的下标
    int index[blocks], maxIndex[blocks];
    for (int i = 0; i < blocks; i++) {
    
    
        index[i] = i * blockSize;
        maxIndex[i] = (i + 1) * blockSize - 1;
        if (maxIndex[i] >= n) {
    
    
            maxIndex[i] = n - 1;
        }
    }
    // 查找所在块
    int block = -1;
    for (int i = 0; i < blocks; i++) {
    
    
        if (arr[index[i]] <= x && arr[maxIndex[i]] >= x) {
    
    
            block = i;
            break;
        }
    }
    // 块内顺序查找
    if (block == -1) {
    
    
        return -1;
    }
    for (int i = index[block]; i <= maxIndex[block]; i++) {
    
    
        if (arr[i] == x) {
    
    
            return i;
        }
    }
    return -1;
}

5. Summary

Here we learn path sequential search, binary search, and block search, and we must pay attention to the objects and methods they use.
I originally wanted to write a hash function here, but after thinking about it, I should write it when I look up the hash.

6. Description

Rising Star Project: Data Structure and Algorithm, @西安第一感情, Creation Punch 2!

Guess you like

Origin blog.csdn.net/weixin_51496226/article/details/130791972