-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathhash_openAddressing.c
More file actions
101 lines (92 loc) · 1.59 KB
/
Copy pathhash_openAddressing.c
File metadata and controls
101 lines (92 loc) · 1.59 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
#include <stdio.h>
#include <stdlib.h>
#define SIZE 10
#define EMPTY -1
#define DELETED -2
int hash(int value);
int search(int value);
void insert(int value);
void delete(int value);
void traverse();
int hash_table[SIZE];
int count = 0;
int main(){
int i;
for(i=0;i<SIZE;i++){
hash_table[i] = EMPTY;
}
traverse();
insert(1);
traverse();
insert(2);
traverse();
insert(3);
traverse();
insert(4);
traverse();
insert(5);
traverse();
insert(6);
traverse();
delete(1);
traverse();
delete(6);
traverse();
}
int hash(int value){
return value % 5;
}
int search(int value){
int i;
int hash_code = hash(value);
for(i=hash_code;i<hash_code+SIZE;i++){
int j = i % SIZE;
if(hash_table[j]==EMPTY){
return -1;
}
if(hash_table[j]==value){
return j;
}
}
return -1;
}
void insert(int value){
if(count >= SIZE){
printf("the hash table is already full!\n");
return;
}
int i = hash(value);
while(hash_table[i] != EMPTY && hash_table[i] != DELETED){
i = (i + 1) % SIZE;
}
hash_table[i] = value;
count++;
}
void delete(int value){
int i;
int hash_code = hash(value);
for(i=hash_code;i<hash_code+SIZE;i++){
int j = i % SIZE;
if(hash_table[j]==EMPTY){
return;
}
if(hash_table[j]==value){
hash_table[j] = DELETED;
count--;
return;
}
}
}
void traverse(){
int i;
for(i=0;i<SIZE;i++){
if(hash_table[i] == EMPTY){
printf("empty ");
}else if(hash_table[i] == DELETED){
printf("deleted ");
}else{
printf("%ld ",hash_table[i]);
}
}
printf("\n");
}