(adsbygoogle = window.adsbygoogle || []).push({ google_ad_client: "ca-pub-2960223314593660", enable_page_level_ads: true }); C program for Hash Table - TecGlance

Header Ads

C program for Hash Table

#include <stdio.h>
#include <stdlib.h>
int search_index(int a[],int index,int size)
{
   int i,j,flag=0;
   for(i=index;i<=size;i++)
   {
      if(a[i]==0)
      {
         flag=1;
         return i;            
      }                     
   }
   if(flag==0)
   {
      for(j=0;j<index;j++)
      {
         if(a[j]==0)
         {
            flag=1;
            return j;           
         }            
      }
   }
}
int main()
{
   int k[100],index,i,j,in[100],size,size2,h,flag=0,item;
   printf("\nEnter the size of the array: ");
   scanf("%d",&size);
   printf("\nEnter the value of 'h': ");
   scanf("%d",&h);
   for(i=0;i<size;i++)
   {
      printf("\nEnter the element: ");
      scanf("%d",&k[i]);
      index=(k[i]%h);
      in[i]=index;                  
   }
/*   for(i=0;i<size;i++)
   {
      printf("\nKey: %d,  Index: %d",k[i],in[i]);                   
   }   */
   size2=0;
   for(i=0;i<size;i++)
   {
      if(in[i]>size2)
      {
         size2=in[i];               
      }
   }
   int hash[size2];
   for(i=0;i<=size2;i++)
   {
      hash[i]=0;                   
   }
   for(i=0;i<size;i++)
   {
      index=in[i];
      if(k[i]==hash[index])
      {
         printf("\nItem already exist! ");
         break;                  
      }    
      if(hash[index]==0)
      {
         hash[index]=k[i];
      }      
      else
      {
         int inde;
         inde=search_index(hash,index,size2);  
        // printf("\nReturned value if index, ie, index of %d is %d: ",k[i],inde); 
         hash[inde]=k[i];
      }
   }
   printf("\nHash table is: ");
   for(i=0;i<=size2;i++)
   {
      if(hash[i]!=0)
      {
         printf("%d:%d ",hash[i],i);                    
   
      }
   }
   getch();
}

No comments

Powered by Blogger.