Monday, February 28, 2011

Hash Search Implementation In Java


10:05 AM | , , , , ,

Hash Search Implementation In Java
Search Tree
import java.io.*;
class hash
{
 public static int a[],ht[];
 public static void main(String args[]) throws IOException
  {
  int a[],n,ch,size;
 
   BufferedReader b=new BufferedReader(new InputStreamReader(System.in)); 
   System.out.println("Enter size of array = ");
   n = Integer.parseInt(b.readLine());
   a = new int[n];
   System.out.println("Enter values = ");
   for(int i=0;i<n;i++)
     a[i] = Integer.parseInt(b.readLine());
   System.out.println("Enter the size of hash table = ");
   size=Integer.parseInt(b.readLine());
    for(int i=0;i<size;i++)
     ht= new int[size];
    store(a,n,ht,size);
 do
        {
                  hashsearch(b,size); 
System.out.println("\n Do you want to continue press 1");
ch=Integer.parseInt(b.readLine());
}while(ch==1);
  }
 
 
public static void store(int x[],int n,int ht[],int size)
{
int i,key,address;
 
for(i=0;i<10;i++)
ht[i]=-1;
for(i=0;i<n;i++)
  {
key=x[i];
address=modulodivison(key,size);
if(ht[address]!=-1)
address=linearprobe(address,size);
ht[address]=key;
}
}
public static int modulodivison(int key,int size)
  {
   int address;
   address=(key%size)+1;
   if(address<size)
           return address;
   else
     return 0;
}
 
public static int linearprobe(int address,int size)
    {
        while(ht[address]!=-1)
    {
        address++;
       if(address==size)
        address=0;
    }
return address;
}
 
 
public static void hashsearch(BufferedReader br,int size)throws IOException
    {
int key,address;
System.out.println("enter the element to be searched");
key=Integer.parseInt(br.readLine());
address=modulodivison(key,size);
while(ht[address]!=-1 && ht[address]!=key)
   {
    address++;
           if(address==size)
    address=0;
}
if(ht[address]==-1)
System.out.println(key +"key is not found");
else
System.out.println(key+"key is found at address"+address);
}}
 
 
 
/*              output
 
Enter size of array =
8
Enter values =
35
66
44
22
84
29
78
57
Enter the size of hash table =
10
enter the element to be searched
78
78key is found at address9
 
 Do you want to continue press 1
1
enter the element to be searched
57
57key is found at address1
 
 Do you want to continue press 1
1
enter the element to be searched
84
84key is found at address8
 
 Do you want to continue press 1
2
 
*/


You Might Also Like :