2024.2.5 作业

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;jdata=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;idata);
			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

2024.2.5 作业_第1张图片

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;
}

2024.2.5 作业_第2张图片

你可能感兴趣的:(哈希算法,散列表,数据结构)