一、实验内容
1.设计一个算法,输出在顺序表{3,6,2,10,1,8,5,7,4,9}中采用顺序方法找
关键字5的过程。
2.设计一个算法,输出在顺序表{1,2,3,4,5,6,7,8,9,10}中采用折半查找法
查找关键字9的过程。
3.设有一组关键字(19,14,23,1,68,20,84,27,56,11,10,79),建立一个哈希查找表。
(1)哈希函数采用:H(key)=key%P(其中P=13),若发生冲突后,用线性探测法解决冲
突;
(2)实现哈希表中关键字的查找。
1.代码实现:
#include<stdio.h>
#include<stdlib.h>
typedef struct
{
int key;
}SqList;
int SeqSearch(SqList R[],int n,int k)
{
int i=0;
while(i<n&&R[i].key!=k)i++;
if(i>=n)
return(-1);
else
return(i);
}
int main()
{
int k=5,i;
SqList R[]={3,6,2,10,1,8,5,7,4,9};
i=SeqSearch(R,10,k);
if(i==-1)
printf("No Found!\n");
else
printf("Found! Post=[%d]\n",i+1);
return 0;
}
1.程序演示:
2.代码实现
#include<stdio.h>
#include<stdlib.h>
typedef struct
{
int key;
}SqList;
int BinSearch(SqList R[],int n,int k)
{
int i,low=0,high=n-1,mid;
int find=0;
while(low<=high&&!find)
{
mid=(low+high)/2;
if(k==R[mid].key)
find=1;
else if(k<R[mid].key)
high=mid-1;
else
low=mid+1;
}
if(find==1)
return mid+1;
else
return -1;
}
int main()
{
int k=9,i;
SqList R[]={1,2,3,4,5,6,7,8,9,10};
i=BinSearch(R,10,k);
if(i==-1)
printf("No Found!\n");
else
printf("Found! Post=[%d]\n",i);
return 0;
}
2.程序演示:
3.代码实现
#include <stdio.h>
#include <string.h>
#define MAX 20
#define NULLKEY -1
typedef int KeyType;
typedef struct
{
KeyType key_num;
}RecordType;
typedef RecordType HashTable[MAX];
HashTable ht;
void Init()
{
int i;
for(i=0;i<MAX;i++)
ht[i].key_num=NULLKEY;
}
int Hash(int key)
{
int mode=key%13;
return mode;
}
int InsertHash(RecordType record)
{
int i,pi,p0=Hash(record.key_num);
if(ht[p0].key_num==NULLKEY)
ht[p0].key_num=record.key_num;
else //如果发生冲突,则用线性探测再散列解决冲突
{
for(i=1;i<=MAX-1;i++)
{ pi=(p0+i)%MAX;
if(ht[pi].key_num==NULLKEY)
{
ht[pi].key_num=record.key_num;
break;
}
}
}
return 1;
}
int Hash_Create()
{
int i,n;
RecordType record[]={19,14,23,1,68,20,84,27,56,11,10,79};
n=sizeof(record)/sizeof(RecordType);
printf("%d\n",n);
for(i=0;i<n;i++)
InsertHash(record[i]);
printf("\nCreate Successfully!\n");
for(i=0;i<MAX;i++)
printf("%3d",i);
printf("\n");
for(i=0;i<MAX;i++)
printf("%3d",ht[i].key_num);
printf("\n");
return 1;
}
int Hash_Search(int key)
{ int p0;
p0=Hash(key);
if(ht[p0].key_num==NULLKEY)
return NULLKEY; //如果为空键值,则表示查找失败
else if(ht[p0].key_num==key)
return p0;
else //用线性探测再散列法解决冲突
{ int i;int pi;
for(i=1;i<=MAX-1;i++)
{ pi=(p0+i)%MAX;
if(ht[pi].key_num==NULLKEY)
return NULLKEY;
else if(ht[pi].key_num==key)
return pi;
}
}
return NULLKEY;
}
int main()
{ int key = NULLKEY;
printf("\n设有一组关键字(19,14,23,1,68,20,84,27,56,11,10,79)");
printf("\n用线性探测再散列方法解决冲突\n");
Init(ht);
Hash_Create(ht);
printf("\nPlease input the key you want Search : \n");
scanf("%d",&key);
key=Hash_Search(key);
if(key!=NULLKEY)
printf("\npost: %d\n", key+1);
else
printf("No found!\n");
return 0;
}
3.程序演示: