# ํด์ ํ ์ด๋ธ์ ๊ฐ์ฅ ํฐ ๋ฌธ์ ๋ ์ถฉ๋(Collision) => Hash Collision
01. Chaining ๊ธฐ๋ฒ
- ๊ฐ๋ฐฉ ํด์ฑ(Open Hashing) ๊ธฐ๋ฒ ์ค ํ๋ -> ํด์ ํ ์ด๋ธ์ ์ ์ฅ๊ณต๊ฐ ์ธ์ ๊ณต๊ฐ์ ํ์ฉํ๋ ๊ธฐ๋ฒ
- ์ถฉ๋ ์, ๋งํฌ๋ ๋ฆฌ์คํธ ์๋ฃ๊ตฌ์กฐ๋ฅผ ์ฌ์ฉํด์ ๋ฐ์ดํฐ๋ฅผ ์ถ๊ฐ๋ก ๋ค์ ์ฐ๊ฒฐ์์ผ ์ ์ฅํ๋ ๊ธฐ๋ฒ
hash_table = list([0 for i in range(8)])
def get_key(data):
return hash(data)
def hash_function(key):
return key % 8
def save_data(data, value):
index_key = get_key(data)
hash_address = hash_function(index_key)
if hash_table[hash_address] != 0:
for index in range(len(hash_table[hash_address])):
if hash_table[hash_address][index][0] == index_key:
hash_table[hash_address][index][1] = value
return
hash_table[hash_address].append([index_key, value])
else:
hash_table[hash_address] = [[index_key, value]]
def read_data(data):
index_key = get_key(data)
hash_address = hash_function(index_key)
if hash_table[hash_address] != 0:
for index in range(len(hash_table[hash_address])):
if hash_table[hash_address][index][0] == index_key:
return hash_table[hash_address][index][1]
return None
else:
return None
save_data('Dd', '1201023010')
save_data('Data', '3301023010')
"""
hash_table =
[0,
0,
[[1341610532875195530, '1201023010'], [-9031202661634252870, '3301023010']],
0,
0,
0,
0,
0]
"""
02. Linear Probing ๊ธฐ๋ฒ
- ํ์ ํด์ฑ(Close Hashing) ๊ธฐ๋ฒ ์ค ํ๋ -> ํด์ ํ ์ด๋ธ์ ์ ์ฅ๊ณต๊ฐ ์์์ ์ถฉ๋ ๋ฌธ์ ๋ฅผ ํด๊ฒฐํ๋ ๊ธฐ๋ฒ
- ์ถฉ๋ ์, ํด๋น hash address์ ๋ค์ address๋ถํฐ ๋งจ ์ฒ์ ๋์ค๋ ๋น ๊ณต๊ฐ์ ์ ์ฅํ๋ ๊ธฐ๋ฒ -> ์ ์ฅ๊ณต๊ฐ ํ์ฉ๋ ๋์
hash_table = list([0 for i in range(8)])
def get_key(data):
return hash(data)
def hash_function(key):
return key % 8
def save_data(data, value):
index_key = get_key(data)
hash_address = hash_function(index_key)
if hash_table[hash_address] != 0:
for index in range(hash_address, len(hash_table)):
if hash_table[index] == 0:
hash_table[index] = [index_key, value]
return
elif hash_table[index][0] == index_key:
hash_table[index][1] = value
return
else:
hash_table[hash_address] = [index_key, value]
def read_data(data):
index_key = get_key(data)
hash_address = hash_function(index_key)
if hash_table[hash_address] != 0:
for index in range(hash_address, len(hash_table)):
if hash_table[index] == 0:
return None
elif hash_table[index][0] == index_key:
return hash_table[index][1]
else:
return None
'์๊ณ ๋ฆฌ์ฆ' ์นดํ ๊ณ ๋ฆฌ์ ๋ค๋ฅธ ๊ธ
[Data Structure] ํธ๋ฆฌ (Tree) (0) | 2024.01.29 |
---|---|
[Data Structure] hash() ํด์ ํจ์ (1) | 2024.01.29 |
[Data Structure] ํด์ ํ ์ด๋ธ (Hash Table) (0) | 2024.01.26 |
[Algorithm] ์๊ณ ๋ฆฌ์ฆ ๋ณต์ก๋ : ์๊ฐ ๋ณต์ก๋ / Big-O (๋น ์ค) ํ๊ธฐ๋ฒ (1) | 2024.01.26 |
[Data Structure] ๋งํฌ๋ ๋ฆฌ์คํธ (Linked List) (1) | 2024.01.26 |