% gcc -o ohash ohash.c > tcc ohash.c % ohash > h h(elp; q(uit; c(reate size; i(nsert x; d(isplay
Data File with Test Cases: ohash.dat
> c 7 i 0 i 81 i 1 i 64 i 4 i 25 i 36 i 16 i 49 i 9 d
Open Hash Table: (size=7)
+-+
0 | |-> 49 -> 0
+-+
1 | |-> 36 -> 64 -> 1
+-+
2 | |-> 9 -> 16
+-+
3 | |
+-+
4 | |-> 25 -> 4 -> 81
+-+
5 | |
+-+
6 | |
+-+
Open Hashing: ohash.c [105]
typedef unsigned int INDEX;
typedef int element_type;
typedef struct list_node *node_ptr;
struct list_node {
element_type element;
node_ptr next;
};
typedef node_ptr LIST;
typedef node_ptr position;
struct hash_tbl {
unsigned int table_size;
LIST *the_lists;
};
typedef struct hash_tbl *HASH_TABLE;
INDEX hash(element_type key, unsigned int H_SIZE) {
return(key % H_SIZE);
}
HASH_TABLE create_hash_table(unsigned int table_size) {
HASH_TABLE H;
int i;
H = (HASH_TABLE) malloc(sizeof(struct hash_tbl));
if (H == NULL) printf("Out of space!\n");
else {
H->table_size = table_size;
H->the_lists = (position *) malloc(sizeof(LIST)*H->table_size);
if (H->the_lists == NULL)
printf("Out of space!\n");
else {
for (i=0; i<H->table_size; i++) {
H->the_lists[i] = (LIST) malloc(sizeof(struct list_node));
if (H->the_lists[i] == NULL)
printf("Out of space!\n");
else
H->the_lists[i]->next = NULL;
}
}
}
return(H);
}
position find(element_type key, HASH_TABLE H) {
position p;
LIST L;
L = H->the_lists[hash(key,H->table_size)];
p = L->next;
while ((p != NULL) && (p->element != key))
p = p->next;
return(p);
}
void insert(element_type key, HASH_TABLE H) {
position pos, new_cell;
LIST L;
pos = find(key,H);
if (pos == NULL) {
new_cell = (position) malloc(sizeof(struct list_node));
if (new_cell == NULL) printf("Out of space!\n");
else {
L = H->the_lists[hash(key,H->table_size)];
new_cell->next = L->next;
new_cell->element = key;
L->next = new_cell;
}
}
}
Open Hashing: Analysis [108]
Define: load factor =
H_SIZE
Good hash function: ``equalizes'' the lengths of lists
H_SIZE prime implies good distribution
H_SIZE = 1 implies
H_SIZE = n implies
Average length of a list =
Insert at head of a list: O( )
Find key somewhere in a list: O( )
Delete somewhere in a list: O( )
Bad hash function: all keys hash to same value
Insert at head of a list: O( )
Find key somewhere in a list: O( )
Delete somewhere in a list: O( )