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--){int flag=0;for(int j=2;j<sqrt(m);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(int key,node hash[],int p)
{int index=key%p;node s=create();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++){printf("%d:",i);node p=hash[i];while(p){printf("%-5d",p->data);p=p->next;}puts("");}
}
int search_key(node hash[],int p,int key)
{int index=key%p;node head=hash[index];while(head!=NULL){if(key==head->data)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;int p=prime(m);for(int i=0;i<len;i++)//把数组元素存到哈希表中{insert_hash(arr[i],hash,p);}//输出哈希表output(hash,m);//查找int key;printf("please enter the key:");scanf("%d",&key);int flag=search_key(hash,p,key);if(flag==0)puts("exist");if(flag==-1)puts("unexist");return 0;
}
2.现有数组{12,23,45,56,445,5676,6888],请输入key实现二分查找
#include<stdio.h>
#include<string.h>
#include<stdlib.h>
int half_search(int arr[],int key,int len,int low,int high)
{while(low<=high){int m=(low+high)/2;if(key>arr[m]){low=m+1;}else if(key==arr[m]){return m;}else {high=m-1;}}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 low=1;int high=len;int key;printf("please enter the search key:");scanf("%d",&key);int index=half_search(arr,key,len,low,high);printf("the search index:%d\n",index);return 0;
}