@@ -12,6 +12,55 @@ def __init__(self, *args, **kwargs):
12
12
super ().__init__ (* args , ** kwargs )
13
13
14
14
def _collision_resolution (self , key , data = None ):
15
+ """
16
+ Quadratic probing is an open addressing scheme used for resolving
17
+ collisions in hash table.
18
+
19
+ It works by taking the original hash index and adding successive
20
+ values of an arbitrary quadratic polynomial until open slot is found.
21
+
22
+ Hash + 1², Hash + 2², Hash + 3² .... Hash + n²
23
+
24
+ reference:
25
+ - https://en.wikipedia.org/wiki/Quadratic_probing
26
+ e.g:
27
+ 1. Create hash table with size 7
28
+ >>> qp = QuadraticProbing(7)
29
+ >>> qp.insert_data(90)
30
+ >>> qp.insert_data(340)
31
+ >>> qp.insert_data(24)
32
+ >>> qp.insert_data(45)
33
+ >>> qp.insert_data(99)
34
+ >>> qp.insert_data(73)
35
+ >>> qp.insert_data(7)
36
+ >>> qp.keys()
37
+ {11: 45, 14: 99, 7: 24, 0: 340, 5: 73, 6: 90, 8: 7}
38
+
39
+ 2. Create hash table with size 8
40
+ >>> qp = QuadraticProbing(8)
41
+ >>> qp.insert_data(0)
42
+ >>> qp.insert_data(999)
43
+ >>> qp.insert_data(111)
44
+ >>> qp.keys()
45
+ {0: 0, 7: 999, 3: 111}
46
+
47
+ 3. Try to add three data elements when the size is two
48
+ >>> qp = QuadraticProbing(2)
49
+ >>> qp.insert_data(0)
50
+ >>> qp.insert_data(999)
51
+ >>> qp.insert_data(111)
52
+ >>> qp.keys()
53
+ {0: 0, 4: 999, 1: 111}
54
+
55
+ 4. Try to add three data elements when the size is one
56
+ >>> qp = QuadraticProbing(1)
57
+ >>> qp.insert_data(0)
58
+ >>> qp.insert_data(999)
59
+ >>> qp.insert_data(111)
60
+ >>> qp.keys()
61
+ {4: 999, 1: 111}
62
+ """
63
+
15
64
i = 1
16
65
new_key = self .hash_function (key + i * i )
17
66
@@ -27,3 +76,9 @@ def _collision_resolution(self, key, data=None):
27
76
break
28
77
29
78
return new_key
79
+
80
+
81
+ if __name__ == "__main__" :
82
+ import doctest
83
+
84
+ doctest .testmod ()
0 commit comments