哈希查找(散列表查找)
步骤:1.确定散列函数及解决冲突的方法
2.根据散列函数建造哈希表
3.进行哈希查找
解决冲突方法:1.开放地址->(1.线性探测 2.线性补偿探测 3.随机探测 4.线性再散列)
2.链表法
---C语言实现
---本次实现散列函数采用除整取余法
---本次实现解决冲突采用链表法
---实现了哈希表的创建 查找
#include <stdio.h>
#include <stdlib.h>
#include <windows.h>
typedef struct hashsraechnode
{
int value;
struct hashsraechnode*pNext;
}HashSraechNode;
//哈希查找(散列表查找)
//散列函数:除整取余
//解决地址冲突:链表法
void HashSearch(int arr[],int length,int SearchNum)
{
int StandardNum;//用数组长度当作标准建造散列函数
HashSraechNode **Head = NULL;
HashSraechNode *Temp = NULL;
HashSraechNode *Del = NULL;
int count;
int IsSearchSucceed;//0:fail 1:success
if(arr == NULL || length <= 0)return ;
IsSearchSucceed = 0;
StandardNum = length;
//建造哈希表
Head = (HashSraechNode **)malloc(sizeof(HashSraechNode *)*StandardNum);
memset(Head,0,sizeof(HashSraechNode*)*StandardNum);
for(count = 0;count<length;count++)
{
Temp = (HashSraechNode *)malloc(sizeof(HashSraechNode ));
Temp->value = arr[count];
Temp->pNext = NULL;
if( !Head[ arr[count]%StandardNum ] )
{
//头添加避免遍历链表
Temp->pNext = Head[ arr[count]%StandardNum ];
Head[ arr[count]%StandardNum ] = Temp;
}
else
{
Head[ arr[count]%StandardNum ] = Temp;
}
}
//哈希查找
if( Head[ SearchNum%StandardNum ] )
{
Temp = Head[ SearchNum%StandardNum ];
while(Temp)
{
if(Temp->value == SearchNum)
{
IsSearchSucceed = 1;
break;
}
Temp = Temp->pNext;
}
}
//释放空间
for(count = 0;count<length;count++)
{
if(Head[count])
{
Temp = Del = Head[count];
while(Temp)
{
Del = Temp;
Temp = Temp->pNext;
free(Del);
Del = NULL;
}
}
}
free(Head);
Head = NULL;
if(IsSearchSucceed)
printf("Search Succeed\n");
else
printf("Search Failed\n");
return ;
}
int main()
{
int arr[] = {2,6,9,12,23,55,67,99,123};
HashSearch(arr,sizeof(arr)/sizeof(arr[0]),6);
system("pause");
return 0;
}