Provide a simple example of Hash Function
Provide a simple example of Hash Function
A hash function is a crucial component of a hash table, which maps data of arbitrary size to fixed-size values, typically integers, that represent the indices in an array where the data is stored. Here is a simple example of a hash function using the modulo operation:
Consider a hash table of size 10. We can use a simple hash function that takes an integer key and returns an index by computing the remainder of the key divided by the size of the hash table. This is known as the division method.
$$ h(k) = k \mod \text{table_size} $$
# Define the size of the hash table
SIZE = 10
# Define a simple hash function using the modulo operator
def hash_function(key):
return key % SIZE
# Example keys to be hashed
keys = [15, 25, 35, 45]
# Compute and print the hash values for the keys
for key in keys:
print(f"Key: {key}, Hash: {hash_function(key)}")
Key: 15, Hash: 5
Key: 25, Hash: 5
Key: 35, Hash: 5
Key: 45, Hash: 5
hash_function(key)
computes the hash value by taking the key modulo the size of the hash table (key % SIZE
).Collisions occur when multiple keys hash to the same index. One common method to handle collisions is linear probing, where you sequentially check the next available slot in the array.
# Initialize the hash table with None values
hash_table = [None] * SIZE
# Insert function with linear probing
def insert(key):
index = hash_function(key)
while ha...
junior
Gợi ý câu hỏi phỏng vấn
Chưa có bình luận nào