散列碰撞
Prerequisite: Hashing data structure
先决条件: 哈希数据结构
碰撞 (Collisions)
Hash functions are there to map different keys to unique locations (index in the hash table), and any hash function which is able to do so is known as the perfect hash function. Since the size of the hash table is very less comparatively to the range of keys, the perfect hash function is practically impossible. What happens is, more than one keys map to the same location and this is known as a collision. A good hash function should have less number of collisions.
哈希函数可以将不同的键映射到唯一的位置(哈希表中的索引),任何能够做到这一点的哈希函数都称为完美哈希函数。 由于哈希表的大小相对于键范围而言非常小,因此理想的哈希函数实际上是不可能的。 发生的事情是,有多个键映射到同一位置,这称为碰撞 。 良好的哈希函数应具有较少的冲突数。
To understand what collision is let's check the below example,
要了解什么是碰撞,让我们检查以下示例,
Say, the set of keys are;
{123, 124, 135, 1267, 2378, 9087}
and hash table size is 10(0-9 indices)
Now,
If our hashing function is
F(x)=digits in x
Then
123->3
124->3
135->3
1267->4
2378->4
9087->4
The hash table will look like,
哈希表看起来像
In the above example, we can see though there are 10 indices only 2 are being used and the collision rate is too high. 123, 124, 135 have collided while 1267, 2378, 9087 have collided.
在上面的示例中,我们可以看到尽管有10个索引,但仅使用了2个,并且冲突率太高。 123、124、135发生了碰撞,而1267、2378、9087发生了碰撞。
#include <bits/stdc++.h>
using namespace std;
//collision
int main()
{
//set of input numbers
vector<int> arr{ 123, 124, 135, 1267, 2378, 9087 };
//using hashh function f(x)=no of digits in x
cout << "using hashh function 1\n";
for (int a : arr) {
cout << a << "->" << to_string(a).length() << endl;
}
return 0;
}
Output:
输出:
using hashh function 1
123->3
124->3
135->3
1267->4
2378->4
9087->4
碰撞解决技术 (Collision Resolution Techniques)
Collision resolution is finding another location to avoid the collision. The most popular resolution techniques are,
碰撞解决方案正在寻找另一个位置来避免碰撞。 最受欢迎的解析技术是
Separate chaining
单独链接
Open addressing
开放式寻址
Open addressing can be further divided into,
开放式寻址可以进一步分为:
Linear Probing
线性探测
Quadratic Probing
二次探测
Double hashing
双重哈希
翻译自: https://www.includehelp.com/data-structure-tutorial/collisions-in-hashing-and-collision-resolution-techniques.aspx
散列碰撞