-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathHashTable.java
More file actions
96 lines (80 loc) · 2.57 KB
/
Copy pathHashTable.java
File metadata and controls
96 lines (80 loc) · 2.57 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
public class HashTable {
static final int SIZE = 20;
static class DataItem {
int data;
int key;
public DataItem(int data, int key) {
this.data = data;
this.key = key;
}
}
static DataItem[] hashArray = new DataItem[SIZE];
static DataItem dummyItem = new DataItem(-1, -1);
static DataItem item;
static int hashCode(int key) {
return key % SIZE;
}
static DataItem search(int key) {
int hashIndex = hashCode(key);
while (hashArray[hashIndex] != null) {
if (hashArray[hashIndex].key == key) {
return hashArray[hashIndex];
}
hashIndex = (hashIndex +1 ) % SIZE;
}
return null;
}
static void insert(int key, int data) {
DataItem item = new DataItem(data, key);
int hashIndex = hashCode(key);
while (hashArray[hashIndex] != null && hashArray[hashIndex].key != -1) {
hashIndex = (hashIndex + 1) % SIZE;
}
hashArray[hashIndex] = item;
}
static DataItem deleteItem(DataItem item) {
int key = item.key;
int hashIndex = hashCode(key);
while (hashArray[hashIndex] != null) {
if (hashArray[hashIndex].key == key) {
DataItem temp = hashArray[hashIndex];
hashArray[hashIndex] = dummyItem;
return temp;
}
hashIndex = (hashIndex + 1) % SIZE;
}
return null;
}
static void display() {
for (int i = 0; i < SIZE; i++) {
if (hashArray[i] != null) {
System.out.print("(" + hashArray[i].key + ", " + hashArray[i].data + ") ");
}
}
System.out.println();
}
public static void main(String[] args) {
insert(1, 20);
insert(2, 70);
insert(42, 80);
insert(4, 25);
insert(12, 44);
insert(14, 32);
insert(17, 11);
insert(13, 78);
insert(37, 97);
System.out.print("Contents of Hash Table:\n");
display();
int element = 37;
System.out.println("The element to be searched " + element);
item = search(37);
if (item != null) {
System.out.println("Element found: " + item.key);
} else {
System.out.println("Element not found");
}
deleteItem(item);
System.out.print("Hash Table contents after deletion: ");
display();
}
}