#include<stdio.h>
#include<string.h>
#include<math.h>
#include<stdlib.h>
typedef int datatype;
//定义结点结构体
typedef struct Node
{datatype data;struct Node *next;
}*node;
//创建结点
node creat_node()
{node s=(node)malloc(sizeof(struct Node));if(NULL==s)//创建失败return NULL;s->data=0;s->next=NULL;return s;
}
//计算最大质数
int prime(int m)
{for(int i=m;i>=2;i--){int flag=0;for(int j=2;j<=sqrt(i);j++){if(i%j==0){flag=-1;break;}}if(flag==0)return i;}
}
//插入
void insert_hash(int key,int p,node hash[])
{int index=key%p; hash[index]; node s=creat_node();s->data=key;if(hash[index]==NULL)hash[index]=s;else{s->next=hash[index];hash[index]=s;}
}
//哈希查找,成功返回0.失败返回-1
int serch_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++){insert_hash(arr[i],p,hash);}datatype key;//查找printf("please enter serch key:");scanf("%d",&key);int flag=serch_hash(key,p,hash);if(flag==0)puts("exits");elseputs("unexits");return 0;
}
#include<stdio.h>
#include<string.h>
#include<stdlib.h>
int half(int key,int *p,int low,int high)
{while(low<=high){int mid=(low+high)/2;if(*(p+mid)<key)low=mid+1;else if(*(p+mid)>key)high=mid-1;else return mid;}return -1;
}
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 input key:");scanf("%d",&key);int i=half(key,arr,0,len-1);if(i==-1)puts("unexist");elseputs("exist");return 0;
}