开放定址散列法和再散列


目录

  1. 开放定址法
  2. 再散列
  3. 代码实现

 

1 开放定址散列法

前面利用分离链接法解决了散列表插入冲突的问题,而除了分离链接法外,还可以使用开放定址法来解决散列表的冲突问题。

开放定址法在遇见冲突情形时,将会尝试选择另外的单元,直到找到空的单元为止,一般来说,单元h0(X), h1(X), h2(x)为相继尝试的单元,则hi(X)=(Hash(X)+F(i)) mod TableSize,其中F(i)即为冲突解决的探测方法,

       开放定址法中的探测方法的三种基本方式为,

  1. 线性探测法:探测步进为线性增长,最基本的方式为F(i)=i
  2. 平方探测法:探测步进为平方增长,最基本的方式为F(i)= i2
  3. 双散列:探测方法的步进由一个新的散列函数决定,最基本的方式为F(i)= i*Hash2(i),通常选择Hash2(i)=R-(X mod R),其中R为小于TableSize的素数。

2 再散列

对于使用平方探测的开放定址散列法,当元素填得太满的时候,操作运行的时间将消耗过长,而且插入操作有可能失败,此时则可以进行一次再散列来解决这一问题。

再散列会创建一个新的散列表,新的散列表大小为大于原散列表大小2倍的第一个素数,随后将原散列表的值重新散列至新的散列表中。

这一操作的开销十分大,但并不经常发生,且在发生前必然已经进行了多次插入,因此这一操作的实际情况并没有那么糟糕。

散列的时机通常有几种,

  1. 装填因子达到一半的时候进行再散列
  2. 插入失败时进行再散列
  3. 达到某一装填因子时进行散列

3 代码实现

完整代码

  1 from functools import partial as pro
  2 from math import ceil, sqrt
  3 from hash_table import HashTable, kmt_hashing
  4 
  5 
  6 class RehashError(Exception):
  7     pass
  8 
  9 
 10 class OpenAddressingHashing(HashTable):
 11     def __init__(self, size, hs, pb, fn=None, rf=0.5):
 12         self._array = [None for i in range(size)]
 13         self._get_hashing = hs
 14         self._hashing = hs(size) if not fn else fn
 15         self._probing = pb
 16         self._rehashing_factor = rf
 17 
 18     def _sniffing(self, item, num, hash_code=None):
 19         # Avoid redundant hashing calculation, if hashing calculation is heavy, this would count much.
 20         if not hash_code:
 21             hash_code = self._hashing(item)
 22         return (hash_code + self._probing(num, item, self.size)) % self.size
 23 
 24     def _get_rehashing_size(self):
 25         size = self.size * 2 + 1
 26         while not is_prime(size):
 27             size += 1
 28         return size
 29 
 30     def rehashing(self, size=None, fn=None):
 31         if not size:
 32             size = self._get_rehashing_size()
 33         if size <= (self.size * self.load_factor):
 34             raise RehashError('Rehash size is too small!')
 35         array = self._array
 36         self._array = [None for i in range(size)]
 37         self._hashing = self._get_hashing(size) if not fn else fn
 38         self.insert(filter(lambda x: x is not None, array))
 39 
 40     def find(self, item):
 41         hash_code = ori_hash_code = self._hashing(item)
 42         collision_count = 1
 43         value = self._array[hash_code]
 44 
 45         # Build up partial function to shorten time consuming when heavy sniffing encountered.
 46         collision_handler = pro(self._sniffing, hash_code=ori_hash_code)
 47 
 48         while value is not None and value != item:
 49             hash_code = collision_handler(item, collision_count)
 50             value = self._array[hash_code]
 51             collision_count += 1
 52         return value, hash_code
 53 
 54     def _insert(self, item):
 55         if item is None:
 56             return
 57         value, hash_code = self.find(item)
 58         if value is None:
 59             self._array[hash_code] = item
 60         if self.load_factor > self._rehashing_factor:
 61             self.rehashing()
 62 
 63 
 64 def is_prime(num):  # O(sqrt(n)) algorithm
 65     if num < 2:
 66         raise Exception('Invalid number.')
 67     if num == 2:
 68         return True
 69     for i in range(2, ceil(sqrt(num))+1):
 70         if num % i == 0:
 71             return False
 72     return True
 73 
 74 
 75 def linear_probing(x, *args):
 76     return x
 77 
 78 
 79 def square_probing(x, *args):
 80     return x**2
 81 
 82 
 83 def double_hashing(x, item, size, *args):
 84     r = size - 1
 85     while not is_prime(r):
 86         r -= 1
 87     return x * (r - (item % r))
 88 
 89 
 90 def test(h):
 91     print('\nShow hash table:')
 92     h.show()
 93 
 94     print('\nInsert values:')
 95     h.insert(range(9))
 96     h.show()
 97 
 98     print('\nInsert value (existed):')
 99     h.insert(1)
100     h.show()
101 
102     print('\nInsert value (collided):')
103     h.insert(24, 47)
104     h.show()
105 
106     print('\nFind value:')
107     print(h.find(7))
108     print('\nFind value (not existed):')
109     print(h.find(77))
110 
111     print('\nLoad factor is:', h.load_factor)
112 
113 
114 if __name__ == '__main__':
115     test(OpenAddressingHashing(11, kmt_hashing, linear_probing))
116     print(30*'-')
117     test(OpenAddressingHashing(11, kmt_hashing, square_probing))
118     print(30*'-')
119     test(OpenAddressingHashing(11, kmt_hashing, double_hashing))
View Code

相关文章: