哈希表——直接定址法

来源:互联网 发布:怎么查淘宝卖家的电话 编辑:程序博客网 时间:2024/05/17 07:03

        哈希表(Hash table,也叫散列表),是根据关键码值(Key value)而直接进行访问的数据结构。也就是说,它通过把关键码值映射到表中一个位置来访问记录,以加快查找的速度。这个映射函数叫做散列函数,存放记录的数组叫做散列表。

       哈希表的做法其实很简单,就是把Key通过一个固定的算法函数既所谓的哈希函数转换成一个整型数字,然后就将该数字对数组长度进行取余,取余结果就当作数组的下标,将value存储在以该数字为下标的数组空间里。

       而当使用哈希表进行查询的时候,就是再次使用哈希函数将key转换为对应的数组下标,并定位到该空间获取value,如此一来,就可以充分利用到数组的定位性能进行数据定位


下面是代码实现

“test.cpp”

<strong><span style="font-size:18px;">#define _CRT_SECURE_NO_WARNINGS 1#include <iostream>using namespace std;#include "HashFunc.h"void Test1(){HashTable<int> ht(10);ht.Insert(89);ht.Insert(18);ht.Insert(49);ht.Insert(58);ht.Insert(9);ht.Print();cout<<ht.Find(58)<<endl;cout<<endl;ht.Remove(49);cout<<"9 exist?"<<ht.Find(9)<<endl;}void Test2(){HashTable<int> ht(5);int j = 4;for (int i = 0;i < 10;i++){ht.Insert(i*j);j++;}ht.Print();cout<<ht.Capacity()<<endl;}int main(){//Test1();Test2();system("pause");return 0;}</span></strong>


"HashTable.h"

<strong><span style="font-size:18px;">#pragma onceenum State{EMPTY,//空状态EXIST,//存在状态DELETE,//删除状态};template<class K>struct __HashFunc{size_t operator()(const K& key){return key;}};template<class K,class HashFunc = __HashFunc<K>>class HashTable{public:HashTable(const size_t capacity):_size(0),_capacity(capacity),_table(new K[capacity]),_state(new State[capacity]){}~HashTable(){if (_table){delete[] _table;_table = NULL;}if (_state){delete[] _state;_state = NULL;}_size = 0;_capacity = 0;}public:int Find(const K& key){size_t index = _HashFunc(key);while (_state[index] != EMPTY){if (_table[index] == key){if (_state[index] == DELETE){return -1;}return index;}++index;if (index == _capacity){index = 0;}}return -1;}bool Insert(const K& key){_CheckCapacity();size_t index = _HashFunc(key);while (_state[index] == EXIST){if (_table[index] == key){return false;}++index;if (index == _capacity){index = 0;}}_table[index] = key;_state[index] = EXIST;_size++;return true;}bool Remove(const K& key){size_t index = Find(key);if (index == -1){return false;} else{_state[index] = DELETE;_size--;return true;}}void Print(){for (int i = 0;i < _capacity;i++){cout<<"["<<_state[i]<<"]: "<<_table[i]<<endl;}}size_t Size(){return _size;}size_t Capacity(){return _capacity;}protected:size_t _HashFunc(const K& key){HashFunc hashfunc;return hashfunc(key) % _capacity;}void _CheckCapacity(){//负载因子大于等于0.7时,增容//负载因子 = 元素个数/数组长度if (_size*10/_capacity >= 7){HashTable<K,HashFunc> tmp(2*_capacity);for (int i = 0;i < _capacity;i++){if (_state[i] == EXIST){tmp.Insert(_table[i]);}}this->_Swap(tmp);}}void _Swap(HashTable<K,HashFunc>& ht){swap(_size,ht._size);swap(_capacity,ht._capacity);swap(_table,ht._table);swap(_state,ht._state);}private:size_t _size;size_t _capacity;K* _table;State* _state;};</span></strong>



0 0
原创粉丝点击