int size = 5; int[] hashTable = new int[size]; Arrays.fill(hashTable, -1); int[] keys = {10, 20, 30, 40}; for (int key : keys) { int index = key % size; while (hashTable[index] != -1) { index = (index + 1) % size; } hashTable[index] = key; } System.out.println(Arrays.toString(hashTable));
The hash function is key % 5. For keys 10, 20, 30, 40, the initial indices are all 0, 0, 0, and 0 respectively.
Insert 10 at index 0.
Insert 20: index 0 occupied, probe to index 1.
Insert 30: probes to index 2.
Insert 40: probes to index 3.
Final state: [10, 20, 30, 40, -1]
int size = 7; int[] hashTable = {14, 21, 28, -1, -1, -1, -1}; int key = 28; int index = key % size; int startIndex = index; while (hashTable[index] != key) { index = (index + 1) % size; if (index == startIndex || hashTable[index] == -1) { index = -1; break; } } System.out.println(index);
Key 28 hashes to 28 % 7 = 0. Index 0 has 14, not 28, so probe next index 1 with 21, still not 28, probe index 2 which has 28. So index 2 is returned.
public void insert(int key) { int index = key % size; while (hashTable[index] != -1) { index = (index + 1) % size; } hashTable[index] = key; }
If the hash table is full, the while loop never finds an empty slot (-1), so it keeps cycling through indices endlessly causing an infinite loop.
Linear probing places collided keys in the next free slot, which can create clusters of consecutive occupied slots, called primary clustering.
int size = 7; int[] hashTable = new int[size]; Arrays.fill(hashTable, -1); // Insert 10 int index = 10 % size; while (hashTable[index] != -1 && hashTable[index] != -2) { index = (index + 1) % size; } hashTable[index] = 10; // Insert 24 index = 24 % size; while (hashTable[index] != -1 && hashTable[index] != -2) { index = (index + 1) % size; } hashTable[index] = 24; // Insert 31 index = 31 % size; while (hashTable[index] != -1 && hashTable[index] != -2) { index = (index + 1) % size; } hashTable[index] = 31; // Delete 24 index = 24 % size; while (hashTable[index] != 24) { index = (index + 1) % size; } hashTable[index] = -2; // Insert 17 index = 17 % size; while (hashTable[index] != -1 && hashTable[index] != -2) { index = (index + 1) % size; } hashTable[index] = 17; System.out.println(Arrays.toString(hashTable));
Insert 10: 10 % 7 = 3 → index 3: 10
Insert 24: 24 % 7 = 3 occupied → probe 4: 24
Insert 31: 31 % 7 = 3 occ → 4 occ → 5: 31
Delete 24: start at 3 (10 !=24) → 4: set to -2
Insert 17: 17 % 7 = 3 occ → 4 (-2): stop and insert 17
Final: [-1, -1, -1, 10, 17, 31, -1]
