-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathhash1.cpp
More file actions
86 lines (75 loc) · 1.67 KB
/
hash1.cpp
File metadata and controls
86 lines (75 loc) · 1.67 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
#include <iostream>
#include <cstdlib>
#define TABLE_SIZE 10
using namespace std;
int h[TABLE_SIZE] = {0};
void insert()
{
int key, index, i, hkey;
cout << "\nEnter a value to insert into the hash table: ";
cin >> key;
hkey = key % TABLE_SIZE;
for (i = 0; i < TABLE_SIZE; i++)
{
index = (hkey + i * i) % TABLE_SIZE;
if (h[index] == 0)
{
h[index] = key;
return;
}
}
cout << "\nElement cannot be inserted\n";
}
void search()
{
int key, index, i, hkey;
cout << "\nEnter search element: ";
cin >> key;
hkey = key % TABLE_SIZE;
for (i = 0; i < TABLE_SIZE; i++)
{
index = (hkey + i * i) % TABLE_SIZE;
if (h[index] == key)
{
cout << "Value is found at index " << index << endl;
return;
}
if (h[index] == 0)
break;
}
cout << "\nValue is not found\n";
}
void display()
{
cout << "\nElements in the hash table are:\n";
for (int i = 0; i < TABLE_SIZE; i++)
{
cout << "At index " << i << "\t value = " << h[i] << endl;
}
}
int main()
{
int opt;
while (true)
{
cout << "\nPress 1. Insert\t 2. Display \t3. Search \t4. Exit\n";
cin >> opt;
switch (opt)
{
case 1:
insert();
break;
case 2:
display();
break;
case 3:
search();
break;
case 4:
exit(0);
default:
cout << "Invalid option! Try again." << endl;
}
}
return 0;
}