JAVA program to perform search using hash function

Posted On // Leave a Comment
Save as "hasing.java"

import java.util.Scanner;

public class hashing
{

static int hashtable[]=new int[100];

public static void clear(int a[])
{
for(int i=0;i<100;i++)
 a[i]=0;
}
public static int findpos(int d)
{
int p=0,s1,s2;
int sq;
sq=d*d;
s2=sq%10;
sq=sq/10;
s1=sq%10;
p=s1*10+s2;
return p;
}


public static int hash(int d)
{
int pos,count=1,t;
pos=findpos(d);
System.out.print(pos);
t=pos;
while(hashtable[pos]!=0)
{
 pos=t+count*count;
 if(pos>99)
 pos=pos%100;
 count++;

}
hashtable[pos]=d;
return pos;
}


public static int search(int d)
{
int pos,count=1,t;
pos=findpos(d);
t=pos;
while(hashtable[pos]!=d)
{
 pos=pos+count*count;
 if(pos>99)
 pos=pos-100;
  if(pos>=t)
 break;
 count++;
}
return pos;
}

public static void main(String args[])
{
int ch,d,flag;
Scanner scan=new Scanner(System.in);
clear(hashtable);
do
{
System.out.println("Menu\n1.Input\n2.Search\n3.display\n4.exit\nEnter ur choice:");
ch=scan.nextInt();
switch(ch)
{
case 1:System.out.println("\nEnter value:");
d=scan.nextInt();
hash(d);break;
case 2:System.out.println("\nEnter value to be searched:");
d=scan.nextInt();
flag=search(d);
System.out.println("Element is found at"+flag);break;
  case 3:for(int i=0;i<100;i++)
          System.out.println("\ntable["+i+"]:"+hashtable[i]);break;
case 4:break;
}
}while(ch!=4);
}
}

0 comments :

Post a Comment