//比较前面的hash值是否有相同,有一样的表示不可取,返回1,没有相同的返回0 int hashCompare(int i,Link_Node_Ptr x) { int j; for(j=0;j<i;j++) { if(hashFun(j,(uint8_t *)x->data,strlen(x->data),HASH_TABLE_LEN)==hashFun(i,(uint8_t *)x->data,strlen(x->data),HASH_TABLE_LEN))return 1; } return 0; }
//找到对应hash值最小的第一个bucket int hashMinIndex(Link_Node_Ptr node) { int i,j,index; uint32_t k; int min[HASH_FUN_COUNT]; for(i=0;i<HASH_FUN_COUNT;i++) { min[i] = hashFun(i,(uint8_t*)node->data,strlen(node->data),HASH_TABLE_LEN); } k = uint32_t_max; for(j=0;j<HASH_FUN_COUNT;j++) { if(k>=Hash_Table[min[j]]->counter) { k = Hash_Table[min[j]]->counter; } } index = HASH_TABLE_LEN; for(j=0;j<HASH_FUN_COUNT;j++) { if(k==Hash_Table[min[j]]->counter && index>=min[j]) { index = min[j]; } } return index; }
//hash_insert void tableInsert(HT hashTable, ElemType *words, int (*hashFun)(ElemType *word, int size)){ ElemType keyTemp[keySize]; strcpy(keyTemp, words); //re-order the words from dictionary sortWords(keyTemp); //calculate hash value int hValue = hashFun(keyTemp, hashTable->tableSize); /* if (strcmp(words, "ably") == 0 || strcmp(words, "boas") == 0) { */ /* printf("%s %d\n", words, hValue); */ /* } */ //add words to bucket addFront(hashTable, hValue, words); }// end of tableInsert
LLBC_Dictionary::Iter LLBC_Dictionary::Find(const LLBC_String &key) { LLBC_KeyHashAlgorithm *hashAlgo = LLBC_KeyHashAlgorithmSingleton; const LLBC_KeyHashAlgorithm::HashBase &hashFun = *hashAlgo->GetAlgorithm(LLBC_CFG_OBJBASE_DICT_KEY_HASH_ALGO); uint32 hash = hashFun(key.c_str(), key.size()) % _bucketSize; LLBC_DictionaryElem *elem = _bucket[hash]; for (; elem != NULL; elem = elem->GetBucketElemNext()) { if (elem->IsStrKey() && *elem->GetStrKey() == key) { return Iter(elem); } } LLBC_SetLastError(LLBC_ERROR_NOT_FOUND); return this->End(); }
void insertItem(char *data) { int i; int index; Link_Node_Ptr node; Link_Node_Ptr x = createNode(data); Link_Node_Ptr Y = insertNode(NULL,x); for(i=0;i<HASH_FUN_COUNT;i++) { if(hashCompare(i,x)==0) { int bucket = hashFun(i,(uint8_t*)x->data,strlen(x->data),HASH_TABLE_LEN); Y = insertNode(Hash_Table[bucket]->node,Y); Hash_Table[bucket]->node = NULL; Hash_Table[bucket]->counter ++; } } while((node=getNode(&Y))) { index = hashMinIndex(node); Hash_Table[index]->node = insertNode(Hash_Table[index]->node,node); } }