哈希算法 散列表 数据结构 2027.2.5 作业 - ,p-&gt

📅 2026-11-30 👤 拼多多助力营销技巧 📂 拼多多助力平台 👁️ 228 次阅读

1.请编程实现哈希表的创建存储数组{12,24,234,234,23,234,23},输入key查找的值,实现查找功能

#include

#include

#include

#include

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

{

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

{

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

hash[i]=NULL;

int p=prime(m);

for(int i=0;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

#include

#include 拼多多帮助力入口

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;

}

推荐链接,哈希算法

标签: 拼多多助力网站平台 赚钱项目 拼多多助力网 首码项目 手赚APP
拼多多助力营销技巧