int table[10] = {-1,-1,-1,-1,-1,-1,-1,-1,-1,-1}; int keys[] = {5, 15, 25}; for(int i=0; i<3; i++) { int key = keys[i]; int idx = key % 10; while(table[idx] != -1) { idx = (idx + 1) % 10; } table[idx] = key; } // Print table contents
Each key hashes to index 5 (5 % 10 = 5, 15 % 10 = 5, 25 % 10 = 5). The first key 5 is placed at index 5. The next key 15 finds index 5 occupied, so it moves to index 6. The key 25 finds indices 5 and 6 occupied, so it moves to index 7.
int table[7] = {-1,-1,-1,-1,-1,-1,-1}; int keys[] = {10, 3, 17, 24}; for(int i=0; i<4; i++) { int key = keys[i]; int idx = key % 7; while(table[idx] != -1) { idx = (idx + 1) % 7; } table[idx] = key; } // Search for 24 int search_key = 24; int idx = search_key % 7; int start = idx; while(table[idx] != search_key) { idx = (idx + 1) % 7; if(idx == start) { idx = -1; // not found break; } } // idx is the result
Keys inserted: 10 at index 3 (10 % 7 = 3), 3 at index 3 occupied, so index 4, 17 at index 3 and 4 occupied, so index 5, 24 at index 3,4,5 occupied, so index 6. Searching 24 starts at index 3, moves to 4, 5, then finds 24 at index 6.
int table[5] = {-1,-1,-1,-1,-1}; int key = 12; int idx = key % 5; while(table[idx] != -1) { idx = (idx + 1) % 5; } table[idx] = key; // Insert keys 12, 7, 2, 17, 22, 27 sequentially using this logic
The code does not check if the table is full before probing. When all slots are occupied, the while loop cycles endlessly, causing an infinite loop.
Using a prime number as table size helps distribute keys more uniformly and reduces clustering during linear probing, improving performance.
Insert 10, Insert 3, Insert 17, Delete 3, Insert 24, Insert 31.
What is the final state of the table? Use -1 for empty slots and -2 for deleted slots.
int table[7] = {-1,-1,-1,-1,-1,-1,-1}; // Insert 10 // Insert 3 // Insert 17 // Delete 3 // Insert 24 // Insert 31 // Use linear probing for collisions // -1 empty, -2 deleted
Insert 10 at index 3 (10 % 7 = 3), insert 3 at index 3 occupied, so index 4, insert 17 at index 5, delete 3 at index 4 (mark -2), insert 24 at index 3,4 occupied (4 is deleted but can be reused), so 24 goes to index 4, insert 31 at index 3,4,5 occupied, so index 6.
