forked from HarshCasper/NeoAlgo
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathlinearProbing.java
More file actions
80 lines (68 loc) · 2.27 KB
/
linearProbing.java
File metadata and controls
80 lines (68 loc) · 2.27 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
/*
1.Hashing is most frequently used in case you have operation like search, insert, delete or subset of these because
hashing provides these operations in O(1) time on an average
2.The data is stored in a hash table
3.Collision happens when our hash function give the same hash value for two or more input values in that case we can use
linear probing to avoid collisions.
Steps to be followed:
1.we will create an empty hash table and initialize all of its value as -1 which represent empty cells.
2.Then we will iterate over the input array and compute the hash value of all the keys to be inserted,
put it in appropriate cells if that cell is already filled we will linearly search for next free cell
and then put the key.
3.We have taken hash function as arr[i]%hashSize
*/
import java.util.*;
public class linearProbing {
static int[] linearProbing(int hashSize, int arr[], int arraySize){
int hash_table[] = new int[hashSize];
for(int i = 0; i < hashSize; i++) {
hash_table[i] = -1;
}
for(int i=0;i<arraySize;i++){
if(hash_table[arr[i]%hashSize]==-1){
hash_table[arr[i]%hashSize]=arr[i];
}
else{
int counter=0;
int k=(1+arr[i])%hashSize;
while(counter<hashSize&&hash_table[k]!=-1){
k=(k+1)%hashSize;
counter++;
}
if(counter<hashSize){
hash_table[k]=arr[i];
}
}
}
return hash_table;
}
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("Enter hash size :");
int hashSize = sc.nextInt();
System.out.println("Enter array size :");
int arraySize = sc.nextInt();
int array[]=new int[arraySize];
System.out.println("Enter elements of array :");
for(int i=0;i<arraySize;i++) {
array[i]=sc.nextInt();
}
int hashTable[]= linearProbing(hashSize,array,arraySize);
for(int i=0;i<hashSize;i++) {
System.out.print(hashTable[i]+" ");
}
}
}
/*
Sample input 1:
Enter hash size :
8
Enter array size :
4
Enter elements of array :
15 48 98 63
Output 1:
48 63 98 -1 -1 -1 -1 15
*/
// Time complexity - O(n)
// Space complexity - O(1)