生活随笔
收集整理的這篇文章主要介紹了
mpq算法实现哈希查找
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
用特定的轉化規則,將字符串轉成進制數用一定規則存放。
實現哈希查找
#include
<stdio
.h
>
#include
<ctype
.h
> typedef struct
{
int nHashA
;
int nHashB
;
int bExists
;
}MPQHASHTABLE;
int nTableSize
=40000000;
unsigned long cryptTable
[0x500];
void prepareCryptTable()
{unsigned long seed
= 0x00100001, index1
= 0, index2
= 0, i
;for( index1
= 0; index1
< 0x100; index1
++ ){for( index2
= index1
, i
= 0; i
< 5; i
++, index2
+= 0x100 ){unsigned long temp1
, temp2
;seed
= (seed
* 125 + 3) % 0x2AAAAB;temp1
= (seed
& 0xFFFF) << 0x10;seed
= (seed
* 125 + 3) % 0x2AAAAB;temp2
= (seed
& 0xFFFF);cryptTable
[index2
] = ( temp1
| temp2
);}}
}
unsigned long
HashString( char
*lpszFileName
, unsigned long dwHashType
)
{unsigned char
*key
= (unsigned char
*)lpszFileName
;
unsigned long seed1
= 0x7FED7FED;
unsigned long seed2
= 0xEEEEEEEE;int ch
;while( *key
!= 0 ){ch
= toupper(*key
++);seed1
= cryptTable
[(dwHashType
<< 8) + ch
] ^ (seed1
+ seed2
);seed2
= ch
+ seed1
+ seed2
+ (seed2
<< 5) + 3;}return seed1
;
}void initHashTable(MPQHASHTABLE *lpTable
,int size
)
{int i
;lpTable
=(MPQHASHTABLE *)malloc(sizeof(MPQHASHTABLE)*size
);for( i
=0;i
<size
;i
++){lpTable
->bExists
=0;lpTable
->nHashA
=0;lpTable
->nHashB
=0;}
}
void insertHashTable(MPQHASHTABLE *lpTable
,char
* lpszString
)
{const int
HASH_OFFSET = 0, HASH_A = 1, HASH_B = 2;int nHash
= HashString(lpszString
, HASH_OFFSET);int nHashA
= HashString(lpszString
, HASH_A);int nHashB
= HashString(lpszString
, HASH_B);int nHashStart
= nHash
% nTableSize
;int nHashPos
= nHashStart
;while ( lpTable
[nHashPos
].bExists
!=1 ){nHashPos
= (nHashPos
+ 1) % nTableSize
;}lpTable
[nHashPos
].nHashA
=nHashA
;lpTable
[nHashPos
].nHashB
= nHashB
;}
int
GetHashTablePos( char
*lpszString
, MPQHASHTABLE *lpTable
, int nTableSize
)
{const int
HASH_OFFSET = 0, HASH_A = 1, HASH_B = 2;int nHash
= HashString(lpszString
, HASH_OFFSET);int nHashA
= HashString(lpszString
, HASH_A);int nHashB
= HashString(lpszString
, HASH_B);int nHashStart
= nHash
% nTableSize
;int nHashPos
= nHashStart
;while ( lpTable
[nHashPos
].bExists
){if (lpTable
[nHashPos
].nHashA
== nHashA
&& lpTable
[nHashPos
].nHashB
== nHashB
){return nHashPos
;}else{nHashPos
= (nHashPos
+ 1) % nTableSize
;}if (nHashPos
== nHashStart
) break;}return -1;
}
int
main()
{MPQHASHTABLE *l
;initHashTable(l
,nTableSize
);insertHashTable(l
,"niceday");insertHashTable(l
,"studyday");insertHashTable(l
,"library");printf("%d\nf",GetHashTablePos("niceday",l
,nTableSize
));
}
總結
以上是生活随笔為你收集整理的mpq算法实现哈希查找的全部內容,希望文章能夠幫你解決所遇到的問題。
如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。