由哈希表的定义,采用C++完成了一个学生成绩存储系统,分析过程如下:
由于哈希表是按KEY值存储,我们假设KEY值为一个字符串。hash算法为字符串的前两位大写字母所对应的数字对一个质数的模运算。
int Hash(KeyType c) { int n = c[0] - 'A'+c[1]-'A'+2; return n % Mod; }
哈希表的类定义如下
class HashTable { public: // HashTable(); HashTable(int len); ~HashTable(); bool SearchHash(KeyType K, int &p, int &c,int &s); bool InsertHash(ElemType e); private: ElemType * elem; int count; int sizeindex; };
搜索函数SearchHash
bool HashTable::SearchHash(KeyType K, int &p, int &c,int &s) { c = 0; p = Hash(K); std::string NULLKey = "None"; while (this->elem[p].key != NULLKey && K != this->elem[p].key) { p++; c++;//冲突次数++ } // cout << "after,p = " << p << endl; if (K == this->elem[p].key) { s = elem[p].score; return true; } else return false; }