int hashTable[5] = {-1, -1, -1, -1, -1}; int size = 5; 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; } for (int i = 0; i < size; i++) { std::cout << hashTable[i] << " "; }
Keys are inserted using h(key) = key % 5. For 10, index 0 is free. For 20, index 0 is occupied, so move to 1. For 30, index 0 and 1 are occupied, so move to 2. For 40, indices 0,1,2 are occupied, so move to 3.
int hashTable[7] = {14, 21, 28, 35, 42, 49, 56}; int size = 7; int key = 24; int index = key % size; int start = index; while (hashTable[index] != key) { index = (index + 1) % size; if (index == start || hashTable[index] == -1) { index = -1; break; } } std::cout << index;
Key 24 hashes to index 3. The slot at index 3 contains 35, not 24. Linear probing checks next slots but none contain 24. After full cycle, key not found, so return -1.
void insert(int hashTable[], int size, int key) { int index = key % size; while (hashTable[index] != -1) { index = (index + 1) % size; } hashTable[index] = key; } // hashTable initialized with -1 for empty slots
If the table is full, the while loop cycles endlessly because no slot is -1. There is no condition to stop or report full table.
Directly setting a slot to empty breaks the search chain. Using a 'deleted' marker allows search to continue probing correctly.
Linear probing places collided keys in consecutive slots, creating clusters that grow and increase search times.
