-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathSearchOperationInHashTable.java
More file actions
63 lines (44 loc) · 1.48 KB
/
Copy pathSearchOperationInHashTable.java
File metadata and controls
63 lines (44 loc) · 1.48 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
import java.util.HashMap;
public class SearchOperationInHashTable {
static final int SIZE = 10;
static class DataItem {
int key;
}
static HashMap<Integer, DataItem> hashMap = new HashMap<>();
static int hashCode(int key) {
return key % SIZE;
}
static DataItem search(int key) {
int hashIndex = hashCode(key);
while (hashMap.get(hashIndex) != null) {
if (hashMap.get(hashIndex).key == key) {
return hashMap.get(hashIndex);
}
++hashIndex;
hashIndex %= SIZE;
}
return null;
}
public static void main(String[] args) {
DataItem item1 = new DataItem();
item1.key = 25;
DataItem item2 = new DataItem();
item2.key = 64;
DataItem item3 = new DataItem();
item3.key = 22;
int hashIndex1 = hashCode(item1.key);
hashMap.put(hashIndex1, item1);
int hashIndex2 = hashCode(item2.key);
hashMap.put(hashIndex2, item2);
int hashIndex3 = hashCode(item3.key);
hashMap.put(hashIndex3, item3);
int keyToSearch = 64;
DataItem result = search(keyToSearch);
System.out.println("The element to be searched: " + keyToSearch);
if (result != null) {
System.out.println("Element found");
} else {
System.out.println("Element not found");
}
}
}