//散列表查找算法(Hash) #include#include #define OK 1 #define ERROR 0 #define TRUE 1 #define FALSE 0 #define SUCCESS 1 #define UNSUCCESS 0 #define HASHSIZE 7 #define NULLKEY -32768 typedef int Status; typedef struct { int *elem; //基址 int count; //當前數據元素個數 }HashTable; int m=0; // 散列表表長 /*初始化*/ Status Init(HashTable *hashTable) { int i; m=HASHSIZE; hashTable->elem = (int *)malloc(m * sizeof(int)); //申請內存 hashTable->count=m; for (i=0;i elem[i]=NULLKEY; } return OK; } /*哈希函數(除留余數法)*/ int Hash(int data) { return data % m; } /*插入*/ void Insert(HashTable *hashTable,int data) { int hashAddress=Hash(data); //求哈希地址 //發生沖突 while(hashTable->elem[hashAddress]!=NULLKEY) { //利用開放定址的線性探測法解決沖突 hashAddress=(++hashAddress)%m; } //插入值 hashTable->elem[hashAddress]=data; } /*查找*/ int Search(HashTable *hashTable,int data) { int hashAddress=Hash(data); //求哈希地址 //發生沖突 while(hashTable->elem[hashAddress]!=data) { //利用開放定址的線性探測法解決沖突 hashAddress=(++hashAddress)%m; if (hashTable->elem[hashAddress]==NULLKEY||hashAddress==Hash(data)) return -1; } //查找成功 return hashAddress; } /*打印結果*/ void Display(HashTable *hashTable) { int i; printf( //==============================// ); for (i=0;i count;i++) { printf(%d ,hashTable->elem[i]); } printf( //==============================// ); } int main() { int i,j,result; HashTable hashTable; int arr[HASHSIZE]={13,29,27,28,26,30,38}; printf(***************Hash哈希算法*************** ); //初始化哈希表 Init(&hashTable); //插入數據 for (i=0;i