DS – Hash Search Algorithm Program

#include<stdio.h>
struct node
{
            int data;
            struct node *next;
}*hashtable[5];
 
void openhashing();
void insert(int);
void search(int);
void main()
{
            int choice, num;
            char ch ;
            openhashing();
            while(1)
            {
                        printf(“1.Insert Data  \n”);
                        printf(“2.Search Data \n”);
                        printf(“3.Exit \n”);
                        printf(“Enter your choice:”);
                        scanf(“%d”, &choice);
                        switch(choice)
                        {
                                    case 1 :            printf(“Enter element to insert :”);
                                                            scanf(“%d”,&num);
                                                            insert(num);
                                                            break;
                                    case 2 :            printf(“\nEnter a key to search : “);
                                                            scanf(“%d”,&num);
                                                            search(num);
                                                            break;
                                    case 3 :            exit(1);
                                    default:            printf(“Invalid choice\n\n”);
                        }
            }
}
void openhashing()
{
            int i;
            for(i=0 ; i<5 ; i++)
            {
                        hashtable[i] = NULL;
            }
}
void insert(int element)
{
            struct node *t;
            int rem;
            rem=element%5;
            t=(struct node*)malloc(sizeof(struct node));
            t->data=element;
            t->next=hashtable[rem];
            hashtable[rem]=t;
}
void search(int element)
{
            struct node *t;
            int remainder,found=0;
            remainder=element%5;
            t = hashtable[remainder];
            while(t!=NULL)
            {
                        if(t->data==element)
                        {
                                    found=1;
                                    break;
                        }
                        else
                                    t=t->next;
            }
            if(!found)
                        printf(“Element not found\n\n”);
            else
                        printf(“Element found\n\n”);
}
Scroll to Top