0% found this document useful (0 votes)
5 views

Formatted HashTable LinearProbing Explanation

Uploaded by

jivobol408
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
5 views

Formatted HashTable LinearProbing Explanation

Uploaded by

jivobol408
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 3

Detailed Explanation of Code with Comments

#include <stdio.h> // Includes standard input-output functions like printf()

and scanf()

#include <stdlib.h> // Includes standard library functions (not directly used in

this code)

#define MAX 5 // Defines the size of the hash table (number of slots)

#define mod(x) x % MAX // Macro to calculate the remainder when x is divided by MAX

(hash function)

// Function to handle collision using linear probing

void linear_prob(int a[], int num, int key) {

// 'a[]' is the hash table array, 'num' is the number to insert, 'key' is the hashed

index

if (a[key] == -1) { // If the slot at index 'key' is empty (marked by -1)

a[key] = num; // Insert the number at this slot

} else { // Collision occurs if the slot is occupied

printf("\nCollision detected!!");

int i; // Used for probing to find the next empty slot

for (i = mod(key + 1); i != key; i = mod(++i)) { // Probe in a circular manner

if (a[i] == -1) { // If an empty slot is found

break; // Stop searching

if (i != key) { // If a free slot was found

printf("\nCollision avoided successfully\n");


a[i] = num; // Insert the number at the empty slot

} else { // No free slot available

printf("\nHash table is full\n");

// Function to display the hash table

void display(int a[]) {

short ch, i; // 'ch' for user's choice, 'i' for iteration

printf("\n1. Filtered display\n2. Display all\nEnter choice: ");

scanf("%hd", &ch); // User input for display preference

printf("\nHash table is:\n");

for (i = 0; i < MAX; i++) {

if (a[i] > 0 || ch - 1) { // Display all or non-empty slots based on choice

printf("%d %d\n", i, a[i]); // Print index and value

int main() {

int a[MAX], num, i; // 'a' is the hash table, 'num' stores user input, 'i' is

for loops and user choice

printf("\nCollision handling by linear probing");

for (i = 0; i < MAX; a[i++] = -1); // Initialize the hash table with -1 (empty

slots)
do {

printf("\nEnter the data: ");

scanf("%4d", &num); // Input a 4-digit key

linear_prob(a, num, mod(num)); // Insert the key using linear probing

printf("Do you wish to continue (1/0): ");

scanf("%d", &i); // Continue or exit based on user input

} while (i); // Loop while user chooses to continue

display(a); // Display the hash table

return 0; // End of program

You might also like