-
Notifications
You must be signed in to change notification settings - Fork 0
/
hashfinal.c
109 lines (109 loc) · 2.62 KB
/
hashfinal.c
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
102
103
104
105
106
107
108
109
#include <stdio.h>
#include <stdlib.h>
int *hash, key, flag, i, found;
int size;
void insert(int item) {
int f = 0;
key = (item % size) - 1;
if (hash[key] == -1)
hash[key] = item;
else {
if (key < size - 1) {
for (i = key + 1; i < size; i++) {
if (hash[i] == -1) {
hash[i] = item;
f = 1;
break;
}
}
}
if (!f) {
for (i = 0; i < key; i++) {
if (hash[i] == -1) {
hash[i] = item;
break;
}
}
}
}
}
void search(int item) {
key = (item % size) - 1;
flag = 0;
if (hash[key] == item)
flag = 1;
else {
for (i = key + 1; i < size; i++) {
if (hash[i] == item) {
flag = 1;
key = i;
break;
}
}
}
if (flag == 0) {
for (i = 0; i < key; i++) {
if (hash[i] == item) {
flag = 1;
key = i;
break;
}
}
}
if (flag == 1) {
found = 1;
printf("Item searched was found at position %d!\n", key + 1);
} else {
key = -1;
printf("Item searched was not found in the hash table\n");
}
}
void display() {
printf("Index\tElement\n");
for (i = 0; i < size; i++)
printf("%d\t%d\n", (i - 1 + size) % size, hash[i]);
printf("\n");
}
int main() {
int element, option;
printf("Enter the size of the array: ");
scanf("%d", &size);
hash = (int *)malloc(size * sizeof(int));
if (hash == NULL) {
printf("Memory allocation failed. Exiting the program.\n");
return 1;
}
for (i = 0; i < size; i++)
hash[i] = -1;
do {
printf("\n1. INSERT\n");
printf("2. SEARCH\n");
printf("3. DISPLAY\n");
printf("4. EXIT\n");
printf("Enter your choice: ");
scanf("%d", &option);
switch (option) {
case 1:
printf("Enter the element to be inserted: ");
scanf("%d", &element);
insert(element);
break;
case 2:
printf("Enter element to be searched: ");
scanf("%d", &element);
search(element);
break;
case 3:
display();
break;
case 4:
printf("Exiting the program\n");
break;
default:
printf("Invalid option\n");
break;
}
} while (option != 4);
free(hash);
return 0;
}