Escolar Documentos
Profissional Documentos
Cultura Documentos
TABELA HASH
1 Adalberto Cajueiro
Departamento de Sistemas e Computao
Universidade Federal de Campina Grande
ESTRUTURAS VISTAS AT AGORA
Busca O(log(n))
Busca O(n)
2
POSSVEL?
Add, search, remove em O(1)?
3
RELEMBRANDO: TABELA, MAPA, DICIONARIO
Conceito <chave,valor>
Sigla (chave) Capital (valor)
Operaes
put(K key, V value) -> T[k] = v "MS" "Campo Grande"
get(K key) -> T[k]
remove(K key) -> T[k] = null "PB" "Joo Pessoa"
Capital
Sigla (chave) pos
0 "Campo Grande"
"MS" 0
1 "Joo Pessoa"
"PB" 1
Capital
Funo
"MS" 0
hash "Campo Grande"
"PB" 1 "Joo Pessoa"
"SP" 2 "So Paulo"
"RS" 3 "Porto Alegre"
TABELA DE ACESSO DIRETO
|U| == |T|
remove(Key k) O(1)
T[hash(k)] = null
search(Key k)
return T[hash(key)]
E SE...
Conjunto de chaves (U) for muito grande? Muito maior que
o tamanho da estrutura (T) para armazena-ls?
9 ...
/
/
/ 13
9
...
EXEMPLO
O que acontece se utilizarmos a funo hash
h(k)=k%10 para inserir os elementos {2,5,9,12}?
/
Universo de
Chaves (U) /
2
...
2 /
12 /
5 5
9 ...
/
/
14
/
9
...
COLISES
Tabela hash ideal seria aquela sem coliso
Impossvel quando |U| > m (tamanho da tabela)
Existem mais chaves que posies
Duas ou mais chaves so mapeadas em um mesmo
ndice
Escolher uma boa funo hash para minimizar as
colises
15
RESOLUO DE COLISES (ABORDAGENS)
Endereamento fechado
Elementos com mesmo cdigo hash so colocados na
mesma posio da tabela (chaining)
Na verdade, inseridos na cabea da lista j que existe a idia
que o o elemento inserido ser usado em breve
Endereamento aberto
Chaves com mesmo cdigo hash so colocadas em
posies diferentes
16
ENDEREAMENTO FECHADO: CHAINING
Usar uma lista encadeada
17
EXERCCIO
Implemente as operaes (inserir, remover,
pesquisar) utilizando a resoluo de conflitos by
chaining?
Inserir(T,x)
Remover(T,x)
Pesquisar(T,k)
18
EXERCCIO
Implemente as operaes (inserir, remover,
pesquisar) utilizando a resoluo de conflitos by
chaining?
Inserir(T,x)
Inserir x na cabea de T[h(key(x))];
Remover(T,x)
Deletar x da lista T[h(key(x))];
Pesquisar(T,k)
Buscar x na lista T[h(k)];
19
EXERCCIO
Implemente as operaes (inserir, remover,
pesquisar) utilizando a resoluo de conflitos by
chaining?
Inserir(T,x)
Inserir x na cabea de T[h(key(x))];
Remover(T,x)
Deletar x da lista T[h(key(x))];
Pesquisar(T,k)
Buscar x na lista T[h(k)];
20
EXERCCIO
Qual seria a tabela final considerando
endereamento fechado (resoluo por chaining) e
funo de hash h(k)=k%2 e chaves do universo
K={2,4,6,8}?
21
EXERCCIO
Qual seria a tabela final considerando
endereamento fechado (resoluo por chaining) e
funo de hash h(k)=k%2 e chaves do universo
K={2,4,6,8}?
2
8 6 4 2
4
... ... ... ...
8 /
6
22
FATOR DE CARGA
A funo h faz um hashing uniforme simples
Chaves possuem igual probabilidade de serem
mapeadas para qualquer um dos indices
Cada clula da tabela vai ter um nmero mais ou
menos igual de elementos
Origina a noo de load factor (fator de carga)
(numero medio de elementos em cada lista)
n = nmero de chaves
m = nmero de clulas na tabela
= n/m
Exemplo: qual o fator de carga de uma tabela hash
23
com 50 clulas e 100 chaves?
EXERCCIO
Qual o limite assintoticamente restrito usando o
fator de carga () para uma pesquisa?
...
h(ki) h(kj) h(kn)
i ...
... ... ...
...
T (1+ )
24
Aplicar a
funo hash
EXERCCIO
Quando uma pesquisa ser feita em (1)?
= n/m = O(1)
n = O(m)
T
...
h(ki) h(kj) h(kn)
i ...
... ... ...
...
(1+ )
25
EXERCCIO
Vamos utilizar a funo hash h(k) = k%m (m=10)
para guardar os CPFs. Como vai ficar a tabela?
Ser que tem alguma funo hash melhor?
26
CARACTERSTICAS DA FUNO HASHING
Minimizar o nmero de colises
Satisfazer a hiptese de hashing uniforme
Qualquer chave tem a mesma probabilidade de ser
mapeada em qualquer um dos m slots. Mas difcil
Alguns mtodos ajudam
Diviso
Multiplicao
Consideramos as chaves como nmeros
Fcil de mapear Strings,... para nmeros
27
MTODO DA DIVISO
Usa o resto da diviso para encotrar valores hash
Neste mtodo a funo hash da forma:
Nmero de
h(k) = k mod m clulas da tabela
28
EXERCCIO
Seja K = {2,4,12,10,5}, desenhe a tabela final
considerando as seguintes funes hash (utilize a
resoluo de conflitos por chaining). As tabelas
possuem 2, 5 e 10 clulas
h=k mod 2
h=k mod 5
h=k mod 10
29
MTODO DA DIVISO
O mtodo da diviso garantes boas funcoes de
hashing?
O que basicamente muda entras as funes hash
no mtodo da diviso?
Que valores escolhemos para m?
30
MTODO DA DIVISO
O mtodo da diviso garantes boas funcoes de
hashing?
O que basicamente muda entras as funes hash
no mtodo da diviso?
Que valores escolhemos para m?
32
MTODO DA DIVISO
Suponha que um conjunto de 2000 elementos ser
armazenado em uma tabela hash onde o fator de
carga estimado 3. Qual seria a melhor funo de
hash para o problema usando o mtodo da
diviso?
h(k) = k % m
2000/3 ~ 667
Primos: 673, 677,683, 691, 701, 709, 719, 727, 733,
739, 743, 751, 757, 761, 769, 773, 787, 797, ...
Potencias de 2: 256, 512, 1024, 2048, ...
33
34
EXERCCIO
Suponha as chaves {200, 205, 210, 215, 220, ..., 595}.
Se eu escolher a funo h(k) = k %100. Vai existir coliso
em alguma clula? Se sim, quantas?
Cada clula preenchida ter quatro chaves
Se eu escolher a funo h(k) = k %101. Vai existir coliso?
Se sim, quantas?
Cada clula preenchida ter uma chave
K % 100 K % 101
0 200, 300, 400, 500 Multiplos de 101: 101 202 303 404 505
...
200 205 210 215 220, ... , 295, 300
5 205, 305, 405, 505
... 099 003 008 013 018, ... , 093, 098
10 210, 310, 410, 510 305 310 315 320 325, ... , 395, 40035
... 002 007 012 017 022, ... , 092, 097
405 410 415 420 425, ... , 495, 500
001 006 011 016 021, ... , 091, 096
MTODO DA MULTIPLICAO
Neste mtodo a funo hash da forma:
37
QUESTES DE IMPLEMENTAO
Hashtable HashFunction
AbstractHashtable
HashFunctionClosedAddress
int hash(T element)
AbstractHashtableClosedAddress
HashFunctionDivision
HashtableClosedAddressImpl HashFunctionMultiplication
}
QUESTES DE IMPLEMENTAO
public abstract class AbstractHashtable<T> implements Hashtable<T> {
Object[] table;
int elements;
int COLLISIONS;
HashFunction<T> hashFunction;
public AbstractHashtable(){
elements = 0;
COLLISIONS = 0;
}
protected void initiateInternalTable(int size){
this.table = Util.<T>makeArray(size);
}
@Override
public boolean isEmpty() {
return (elements == 0); 40
}
QUESTES DE IMPLEMENTAO
@Override
public boolean isFull() {
return (elements == table.length);
}
@Override
public int size() {
return elements;
}
@Override
public int capacity(){
return this.table.length;
}
public AbstractHashtableClosedAddress(){
super();
}
@Override
protected void initiateInternalTable(int size){
this.table = Util.<LinkedList<T>>makeArray(size);
}
}
}
QUESTES DE IMPLEMENTAO
43
QUESTES DE IMPLEMENTAO
public class HashFunctionDivisionMethod<T>
implements HashFunctionClosedAddress<T> {
return hashKey;
} 44
}
QUESTES DE IMPLEMENTAO
public class HashFunctionMultiplicationMethod<T>
implements HashFunctionClosedAddress<T>{
return hashKey; 45
}
}
QUESTES DE IMPLEMENTAO
public enum HashFunctionClosedAddressMethod {
DIVISION, MULTIPLICATION;
}
public class HashFunctionFactory<T> {
public static HashFunction
createHashFunction(HashFunctionClosedAddressMethod
method, int tableSize){
HashFunction result = null;
switch (method) {
case DIVISION:
result = new
HashFunctionDivisionMethod(tableSize);
case MULTIPLICATION:
result = new
HashFunctionMultiplicationMethod(tableSize);
}
46
return result;
}
}
QUESTES DE IMPLEMENTAO
public class HashtableClosedAddressImpl<T> extends
AbstractHashtableClosedAddress<T> {
if(method == DIVISION){
realSize = this.getPrimeAbove(desiredSize);
}
initiateInternalTable(realSize);
HashFunction function =
HashFunctionFactory.createHashFunction(method,realSize);
this.hashFunction = function;
}
47
QUESTES DE IMPLEMENTAO
int getPrimeAbove(int number){
//use Util.isPrime(n)
}
49
OUTRA FORMA DE RESOLVER CONFLITOS
Endereamento aberto faz uso de um probe.
Examina a tabela (sequencial ou nao) at encontrar um
slot vazio.
A sequencia de posicoes sendo examinadas dependem
da chave
Funo hash estendida
posicao = h(k,p)
k = chave
50
p = probe
EXEMPLO: INSERO
Insira a chave k=100
Probe h(100,0) /
Probe h(100,1) 100
/
Probe h(100,2) 200
/
/
150
/
/
/
999
51
ALGORITMO: INSERO
52
EXEMPLO: PESQUISA
Pesquisa a chave k=100
Probe h(100,0) /
Probe h(100,1) /
Probe h(100,2) 200
/
/
150
/
/
/
999
53
ALGORITMO: PESQUISA
54
ENDEREAMENTO ABERTO (DELEO)
Como fazer uma remocao com enderecamento
aberto?
Podemos atribuir NIL diretamente na posio da chave
a ser removida?
55
ENDEREAMENTO ABERTO (DELEO)
Como fazer uma remocao com enderecamento
aberto?
Nao podemos simplesmente dizer que o slot esvaziou
colocando NIL
Usar uma flag (valor especial DELETED) ao invs de
NIL
Alterar as funes
Inserir (inserir no flag se ele for DELETED)
Pesquisar (continuar a pesquisa no flag ao invs de NIL)
56
EXEMPLO
Remova a chave k=100
Probe h(100,0)
/
Probe h(100,1) E como ficaria a insero?
100
X
Probe h(100,2)
200
/
/
Pesquisar at achar a 150
chave (remova coloque /
um flag DELETED) ou /
uma clula vazia
/
999
57
EXEMPLO
|| T[j] = DELETED
58
HASHING COM PROBING
Como escolher a funo hash no endereamento
aberto usando o probe?
Por que no utilizar a funo h(k,i) = k%m?
Precisamos usar i para que o endereo mude.
Tres tcnicas so usadas para computar as
sequencias de probes
Linear Probing
Quadratic Probing
Double Hashing
59
LINEAR PROBING
Dada uma funcao de hash ordinaria h': U {0,1,..., m 1}
(obtida por diviso ou multiplicao) o mtodo usa
a funo de hash da forma:
h(k , i ) (h' (k ) i ) mod m
Slots buscados linearmente
T [( h' ( k )]
T [ h' ( k ) 1]
...
T [ m 1]
Facil de implementar mas apresenta problemas
Clustering Primrio clusters podem surgir quando slots
ocupados se agrupam. Isso aumenta o tempo da busca. 60
EXERCCIO
Seja m=10, h(k) = k mod 5. Utilize o probing linear
para inserir os valores ({10,15,2,12,4,8})
61
PROBING QUADRTICO
Neste mtodo a funo hash da forma:
63
EXERCCIO
Compare a resposta anterior com o linear probing e
o endereamento fechado (h(k) = k mod 10) com
chaining para inserir os valores ({10,15,2,12,4,8}):
h(k) = k mod 10
h(k,i) = (k mod 5 + i) mod 10
h(k,i) = (k mod 5 + 3i + 5i2) mod 10
64
HASHING DUPLO
Um dos melhores metodos para endereamento aberto
Neste mtodo a funo hash da forma:
66
POSCOMP 2009
67
POSCOMP 2009
68
FATOR DE CARGA
Qual o fator de carga no endereamento aberto?
O load factor 1
Por que?
69
LIDANDO COM OVERFLOW
O que fazer quando o vetor interno da tabela hash
ficar cheio?
Duplicar quando estiver cheio?
Duplicar quando atingir uma certa capacidade?
70
REHASHING
Quando a capacidade preenchida (exceder 50%),
as operaes na tabela passam a demorar mais,
pois o nmero de colises aumenta
Expandir o array que constitui a tabela, e
reorganizar os elementos na nova tabela
Novo tamanho: nmero primo prximo ao dobro da
tabela atual
71
EXEMPLO
Tamanho = 7
34 40 X 11 95
Tamanho = 13
40 95 34 11
73
IMPLEMENTAO
Hashtable
http://www.docjar.com/html/api/java/util/Hashtable.java.htm
l
Ver funes
hash()
O cdigo hash delegado para cada classe
containsKey()
get()
put()
remove()
rehash()
equals( ) x hashCode( ).
a.equals(b) hashCode(a) = hashCode(b) 74
TABELA HASH (IMPLEMENTAO)
Separando a tabela de sua funo hash?
Hashtable HashFunction
75
QUESTES DE IMPLEMENTAO
Hashtable HashFunction
AbstractHashtable
HashFunctionOpenAddress
int hash(T element)
AbstractHashtableOpenAddress
HashFunctionLinearProbing
HashtableOpenAddressImpl HashFunctionQuadracticProbing
HashFunctionDoubleHashing 76
nica classe que o aluno
precisar editar
QUESTES DE IMPLEMENTAO
public abstract class AbstractHashtableOpenAddress<T>
extends AbstractHashtable<T> {
public AbstractHashtableOpenAddress(){
this.tableSize = tableSize;
this.initiateInternalTable(size);
}
@Override
protected void initiateInternalTable(int size){
this.table = Util.<Storable>makeArray(size);
}
}
public static <T> T[] makeArray(int size) { 77
T[] array = (T[]) new Object[size];
return array;
}
QUESTES DE IMPLEMENTAO
public abstract class AbstractHashtableOpenAddress<T>
extends AbstractHashtable<T> {
public AbstractHashtableOpenAddress(){
this.tableSize = tableSize;
this.initiateInternalTable(size);
}
@Override
protected void initiateInternalTable(int size){
this.table = Util.<Storable>makeArray(size);
}
}
78
public interface Storable {
}
QUESTES DE IMPLEMENTAO
79
QUESTES DE IMPLEMENTAO
public HashFunctionLinearProbing<T> implements
HashFunctionOpenAddress<T> {
protected HashFunctionClosedAddress<T> originalHashFunction;
protected int tableCapacity;
@Override
public int hash(T element, int probe) {
int generatedIndex = 0;
generatedIndex= ((originalHashFunction.hash(element)
+ probe) % this.hashtable.capacity());
return generatedIndex;
}
81
QUESTES DE IMPLEMENTAO
public class HashFunctionQuadraticProbing<T> implements
HashFunctionOpenAddress<T> {
private int tableCapacity;
protected HashFunctionClosedAddress<T> originalHashFunction;
protected int c1;
protected int c2;
public HashFunctionQuadraticProbing(int tableCapacity,
HashFunctionClosedAddressMethod method,int c1, int c2) {
this.tableCapacity = tableCapacity;
if(method == HashFunctionClosedAddressMethod.DIVISION){
originalHashFunction = new
HashFunctionDivisionMethod<T>(tableCapacity);
}else{
originalHashFunction = new
HashFunctionMultiplicationMethod<T>(tableCapacity);
}
this.c1 = c1; 82
this.c2 = c2;
}
QUESTES DE IMPLEMENTAO
@Override
public int hash(T element, int probe) {
int generatedIndex = 0;
generatedIndex = originalHashFunction.hash(element);
generatedIndex = ((generatedIndex + c1*probe +
c2*probe*probe)% tableCapacity);
return generatedIndex;
}
83
QUESTES DE IMPLEMENTAO
public abstract class AbstractHashtableOpenAddress<T extends
Storable> extends AbstractHashtable<T> {
@Override
protected void initiateInternalTable(int size) {
this.table = Util.<Storable>makeArray(size);
}
}
84
QUESTES DE IMPLEMENTAO
public abstract class AbstractHashtableOpenAddress<T extends
Storable> extends AbstractHashtable<T> {
//mtodos a implementar
}
86
QUESTES DE IMPLEMENTAO
public class HashtableOpenAddressQuadraticProbingImpl<T extends
Storable> extends AbstractHashtableOpenAddress<T> {
//mtodos a implementar
}
87
QUESTES DE IMPLEMENTAO
public class HashtableOpenAddressDoubleHashing<T extends
Storable> extends AbstractHashtableOpenAddress<T> {
//mtodos a implementar
}
88
REFERNCIAS
Captulo 11
2a edio
89