int size = 7; int[] hashTable = new int[size]; for (int i = 0; i < size; i++) hashTable[i] = -1; int[] keys = {10, 22, 31, 4, 15}; foreach (int key in keys) { int index = key % size; while (hashTable[index] != -1) { index = (index + 1) % size; } hashTable[index] = key; } // Print hashTable
Each key is inserted at index = key % 7. If occupied, move to next index until empty slot found.
10 % 7 = 3 → slot 3 empty → insert 10
22 % 7 = 1 → slot 1 empty → insert 22
31 % 7 = 3 → slot 3 occupied by 10 → move to 4 empty → insert 31
4 % 7 = 4 → slot 4 occupied by 31 → move to 5 empty → insert 4
15 % 7 = 1 → slot 1 occupied by 22 → move to 2 empty → insert 15
int size = 5; int[] hashTable = {12, 25, 36, -1, 20}; int key = 36; int index = key % size; int startIndex = index; while (hashTable[index] != key) { index = (index + 1) % size; if (index == startIndex || hashTable[index] == -1) { index = -1; // not found break; } } // index is the result
36 % 5 = 1, start searching at index 1.
Index 1 has 25 (not 36), move to 2.
Index 2 has 36, found key at index 2.
int size = 5; int[] hashTable = {1,2,3,4,5}; int key = 10; int index = key % size; while (hashTable[index] != -1) { index = (index + 1); } hashTable[index] = key;
The index increments without modulo operation, so it can exceed array bounds causing IndexOutOfRangeException.
Linear probing is simple and uses contiguous slots, which improves cache locality and performance.
However, it can cause clustering, so option A is incorrect.
It does not guarantee no collisions (B) and does not use linked lists (D).
int size = 10; int[] hashTable = new int[size]; for (int i = 0; i < size; i++) hashTable[i] = -1; int[] keys = {20, 30, 40, 50, 60, 70, 80}; foreach (int key in keys) { int index = key % size; while (hashTable[index] != -1) { index = (index + 1) % size; } hashTable[index] = key; } // Print hashTable
All keys hash to index 0 (key % 10 = 0), so they probe linearly from index 0:
- 20 → index 0
- 30 → index 1
- 40 → index 2
- 50 → index 3
- 60 → index 4
- 70 → index 5
- 80 → index 6
Final hash table: [20, 30, 40, 50, 60, 70, 80, -1, -1, -1]
