1.
int prime(int m)
{
for(int i=m;i>1;i--)
{
int flag=0;
for(int j=2;j<i;j++)
{
if(i%j==0)
{
flag=-1;
break;
}
}
if(flag==0)
return i;
}
}
node create()
{
node s=(node)malloc(sizeof(struct Node));
if(s==NULL)
return NULL;
s->data=0;
s->next=NULL;
return s;
}
void insert_hash(datatype element,int p,node hash[])
{
node s=create();
s->data=element;
int index=element%p;
if(hash[index]==NULL)
hash[index]=s;
else
{
s->next=hash[index];
hash[index]=s;
}
}
void output(node hash[],int m)
{
for(int i=0;i<m;i++)
{
node p=hash[i];
while(p)
{
printf("%-5d",p->data);
p=p->next;
}
puts("NULL");
}
}
int search_hash(datatype key,int p,node hash[])
{
int index=key%p;
node q=hash[index];
int i=0;
while(q)
{
i++;
if(q->data==key)
{
printf("row:%d line:%d\n",index+1,i);
return SUCCESS;
}
q=q->next;
}
return FALSE;
}
int main(int argc, const char *argv[])
{
int arr[]={12,24,234,234,23,234,23};
int len=sizeof(arr)/sizeof(arr[0]);
int m=len*4/3;
node hash[m];
for(int i=0;i<m;i++)
hash[i]=NULL;
int p=prime(m);
for(int i=0;i<m;i++)
insert_hash(arr[i],p,hash);
hash[0]=NULL;
output(hash,m);
int key;
printf("please enter key:");
scanf("%d",&key);
int flag=search_hash(key,p,hash);
if(flag==0)
puts("exists");
else
puts("unexists");
return 0;
}
2.
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
int half(int key,int arr[],int low,int high)
{
while(low<=high)
{
int m=(low+high)/2;
if(arr[m]<key)
low=m+1;
else if(arr[m]>key)
high=m-1;
else
return m;
}
}
int main(int argc, const char *argv[])
{
int arr[]={12,23,45,56,445,5676,6888};
int len=sizeof(arr)/sizeof(arr[0]);
int key;
printf("please enter key:");
scanf("%d",&key);
int index=half(key,arr,0,len-1);
if(index<0 || index>len-1)
puts("unexists");
else
printf("exists is arr[%d]\n",index);
return 0;
}