Linear probing to resolve conflicts-seeking hash addresses

Problem description]
Due to the collision problem in the hash, the storage address of some key codes is not the same as that calculated by the hash function. Later, many solutions were proposed to solve the conflict, of which the linear detection method is one. The so-called linear detection method is to search for an empty hash address in order from the next position of the conflict position when a conflict occurs. In this case, if you want to find a keyword, you must continue to probe, and finally you can find the storage location of the key code. Now you need to count the number of key code comparisons in this process.
Given the set of key codes (the key codes are all greater than zero), the hash table length is maxS, the hash function is H (key) = key% divi, and the linear detection method is used to deal with the conflict.
[Input form] Two integers in the first line, the first one indicates the length of the hash table maxS, the second one indicates the divisor divi; the number of key codes in the second line; the key code sets in the third line, and spaces between data elements Separated; the fourth line indicates the key code to be found.
[Output form] The hash address of the value to be found. If the value to be found does not exist, -1 is output.
[Sample input]
11 11
9
47 7 29 11 16 92 22 8 3
3
[Sample output] 6

Analysis:
1. Create a hash array
2. Write a function that stores the hash to store the input data in the hash array
3. Query the output in the hash array

achieve

Create a function stored in a hash array

void Insert (int maxS,int divi,int k,int ht[])
{//maxS 数组长度 divi 除数 k 要存入的数 ht[] 哈希数组
    int j;
    j=k%divi;
    if(ht[j]==0)//为 0 说明 没有存放数据
        ht[j]=k;
    else if(ht[j]!=0) //有数据 
    {
        int i=j;
        while(ht[i]!=0)
        {
            i=(i+1)%maxS;//利用线性探测 每次加一 
        }
        ht[i]=k;
    }
}

Query subscript function

int Search (int maxS,int divi,int k,int ht[])
{//这里的k和上面的k不同 这个 k 为关键码(key 要查询的数)
    int j;
    j=k%divi;
    int i=j;
    int cnt=0;
    while(ht[i]!=0&&cnt<maxS)//防止因查找不到而死循环
    {
        cnt++;//每次循环 计数器加一
        if(ht[i]==k)
            return i;//找到返回下标
        else
        {
            i=(i+1)%maxS;
        }
    }
    return -1;//如果未找到 返回-1
}

Main function

int main()
{
    int maxS,divi,n,k;
    cin>>maxS>>divi;
    cin>>n;
    int ht[maxS]={0};
    int a[n];
    for(int i=0;i<n;i++)
    {
        cin>>a[i];
    }
    cin>>k;
    for(int k=0;k<n;k++)
    {
        Insert(maxS,divi,a[k],ht);//将输入的数据存入哈希数组当中
    }
    cout<<Search(maxS,divi,k,ht)<<endl;

}

Below is a little white. If there is an inappropriate place, please correct me.

Published 31 original articles · won praise 8 · views 2155

Guess you like

Origin blog.csdn.net/weixin_44034024/article/details/105068669