哈希和二分查找

 

哈希和二分查找_第1张图片 

#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<=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;idata);
			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,23,234,23};
	int len=sizeof(arr)/sizeof(arr[0]);
	int m=len*4/3;
	node hash[m];
	for(int i=0;i

 

哈希和二分查找_第2张图片 

#include
int half(int key,int *p,int low,int high)
{
	while(low<=high)
	{
	int mid=(low+high)/2;
	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 key;
	int len=sizeof(arr)/sizeof(arr[0]);
	printf("please enter key:");
	scanf("%d",&key);
	int index=half(key,arr,0,len-1);
	if(index==-1)
		puts("unexists");
	else
		printf("exists in %d\n",index);
	return 0;
}

 

你可能感兴趣的:(java,算法,数据结构)