-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathHashTable.java
144 lines (122 loc) · 2.49 KB
/
HashTable.java
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
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
/*
Copyright (C) Deepali Srivastava - All Rights Reserved
This code is part of DSA course available on CourseGalaxy.com
*/
package OpenAddressing1;
public class HashTable
{
private studentRecord[] array;
private int m; //size of the array
int n; //number of records
public HashTable()
{
this(11);
}
public HashTable(int tableSize)
{
m = tableSize;
array = new studentRecord[m];
n = 0;
}
public void DisplayTable()
{
for(int i=0; i<m; i++)
{
System.out.print( "[" + i + "] --> " );
if(array[i]!=null && array[i].getstudentId()!=-1)
System.out.println( array[i] );
else
System.out.println("___");
}
}
public studentRecord Search(int key)
{
int h = hash(key);
int location=h;
for(int i=1; i<m ; i++)
{
if( array[location]==null)
return null;
if(array[location].getstudentId() == key)
return array[location];
location = (h+i)%m;
}
return null;
}
public void Insert1(studentRecord newRecord)
{
if (n >= m/2)
{
rehash( nextPrime(2*m) );
System.out.println( "New Table Size is : " + m );
}
Insert(newRecord);
}
public void Insert(studentRecord newRecord)
{
int key = newRecord.getstudentId();
int h = hash(key);
int location = h;
for( int i=1; i<m; i++)
{
if( array[location]==null || array[location].getstudentId()==-1 )
{
array[location]=newRecord;
n++;
return;
}
if(array[location].getstudentId() == key)
throw new UnsupportedOperationException("Duplicate key");
location = (h+i)%m;
}
}
public void Delete(int key)
{
int h = hash(key);
int location=h;
for(int i=1; i<m ; i++)
{
if( array[location]==null)
return;
if(array[location].getstudentId() == key)
{
array[location].setstudentId(-1);
n--;
if (n > 0 && n <= m/8)
{
rehash(nextPrime(m/2));
System.out.println( "New Table Size is : " + m );
}
}
location = (h+i)%m;
}
}
int hash(int key)
{
return(key%m);
}
private void rehash(int newSize)
{
HashTable temp = new HashTable(newSize);
for (int i = 0; i < m; i++)
if (array[i] != null && array[i].getstudentId()!=-1)
temp.Insert(array[i]);
array = temp.array;
m = newSize;
}
int nextPrime(int x)
{
while( !isPrime(x) )
x++;
return x;
}
boolean isPrime(int x)
{
for(int i=2; i<x; i++)
{
if(x%i==0)
return false;
}
return true;
}
}