-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathhashing_linear.c
More file actions
71 lines (47 loc) · 1.18 KB
/
hashing_linear.c
File metadata and controls
71 lines (47 loc) · 1.18 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
#include <stdio.h>
#define SIZE 10
int hashTable[SIZE];
int EMPTY = -1;
int hash(int key) {
return key % SIZE;
}
void insert(int key) {
int index = hash(key);
for (int i = 0; i < SIZE; i++) {
int newIndex = (index + i) % SIZE;
if (hashTable[newIndex] == EMPTY) {
hashTable[newIndex] = key;
printf("Inserted %d at index %d\n", key, newIndex);
return;
}
}
printf("Hash Table is full! Cannot insert %d\n", key);
}
void search(int key) {
int index = hash(key);
for (int i = 0; i < SIZE; i++) {
int newIndex = (index + i) % SIZE;
if (hashTable[newIndex] == key) {
printf("Key %d found at index %d\n", key, newIndex);
return;
}
if (hashTable[newIndex] == EMPTY) {
printf("Key %d NOT found!\n", key);
return;
}
}
printf("Key %d NOT found!\n", key);
}
int main() {
for (int i = 0; i < SIZE; i++) {
hashTable[i] = EMPTY;
}
insert(12);
insert(22);
insert(42);
insert(52);
search(22);
search(52);
search(7);
return 0;
}