1.请编程实现哈希表的创建存储数组(12,24,234,234,23,234,23),输入key查找的值,实现查找功能
#include<stdio.h>
#include<string.h>
#include<stdlib.h>
#include<math.h>
typedef int datatype;
//定义节点结构体
typedef struct Node
{
//数据域
datatype data;
//指针域
struct Node *next;
}*node;
//计算最大质数
int prime(int m)
{
for(int i=m;i>=2;i--)
{
//判断i是否为质数
int flag=0;
for(int j=2;j<=sqrt(i);j--)
{
if(i%j==0)
{
flag=-1;
break;
}
}
if(flag==0)
return i;
}
}
//创建新节点
node create_node()
{
node s=(node)malloc(sizeof(struct Node));
if(NULL==s)
return NULL;
s->data=0;
s->next=NULL;
return s;
}
//插入
void insert_hash(int key,int p,node hash[])
{
int index=key%p;//哈希函数
// hash[index];//等价于单链表的头指针
//创建新节点
node s=create_node();
s->data=key;
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++)
{
for(node j=hash[i];j!=NULL;j=j->next)
{
printf("%d:%-5d",i,j->data);
}
printf("%d:",i);
node p=hash[i];
while(p!=NULL)
{
printf("%-5d",p->data);
p=p->next;
}
puts("NULL");
}
}
//哈希查找
int search_hash(datatype key,int p,node hash[])
{
int index=key%p;
node head=hash[index];
while(head!=NULL)
{
if(head->data==key)
return 0;
head=head->next;
}
return -1;
}
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;
//定义函数计算p:不大于哈希表长度的最大质数
int p=prime(m);
//把数组元素一次存到哈希表中
for(int i=0;i<len;i++)
{
//arr[i];
//把arr[i]数组元素插入到哈希表中
insert_hash(arr[i],p,hash);
}
//输出哈希表
output(hash,m);
//查找
datatype key;
printf("please enter search key:");
scanf("%d",&key);
int flag=search_hash(key,p,hash);
if(flag==0)
puts("exists");
else
puts("unexists");
return 0;
}
2.现有数组12,23,45,56,445,5676,6888请输入key实现二分查找
//折半查找
int half(int key,int arr[],int low,int high)
{
while(low<=high)
{
int mid=(low+high)/2;
if(arr[mid]<key)
{
low=mid+1;
}
else if(arr[mid]>key)
{
high=mid-1;
}
else
return mid;
}
return -1;
}