-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathhashing.cpp
More file actions
75 lines (63 loc) · 1.76 KB
/
hashing.cpp
File metadata and controls
75 lines (63 loc) · 1.76 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
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define SIZE 10
struct KeyValue {
char* key;
int value;
};
struct KeyValue* hashTable[SIZE];
int hash(char* key) {
int sum = 0;
for (int i = 0; key[i] != '\0'; i++) {
sum += key[i];
}
return sum % SIZE;
}
void insert(char* key, int value) {
int index = hash(key);
while (hashTable[index] != NULL) {
index = (index + 1) % SIZE;
}
hashTable[index] = (struct KeyValue*)malloc(sizeof(struct KeyValue));
hashTable[index]->key = strdup(key);
hashTable[index]->value = value;
}
int search(char* key) {
int index = hash(key);
while (hashTable[index] != NULL) {
if (strcmp(hashTable[index]->key, key) == 0) {
return hashTable[index]->value;
}
index = (index + 1) % SIZE;
}
return -1; // Key not found
}
void display() {
printf("Hash Table:\n");
for (int i = 0; i < SIZE; i++) {
if (hashTable[i] != NULL) {
printf("[%d] -> %s:%d\n", i, hashTable[i]->key, hashTable[i]->value);
} else {
printf("[%d] -> NULL\n", i);
}
}
}
int main() {
// Initialize hash table
for (int i = 0; i < SIZE; i++) {
hashTable[i] = NULL;
}
insert("apple", 10);
insert("banana", 20);
insert("orange", 30);
insert("grape", 40);
display();
printf("\nSearch results:\n");
printf("Value for 'apple': %d\n", search("apple"));
printf("Value for 'banana': %d\n", search("banana"));
printf("Value for 'orange': %d\n", search("orange"));
printf("Value for 'grape': %d\n", search("grape"));
printf("Value for 'cherry': %d\n", search("cherry"));
return 0;
}