File tree Expand file tree Collapse file tree 2 files changed +105
-0
lines changed
Expand file tree Collapse file tree 2 files changed +105
-0
lines changed Original file line number Diff line number Diff line change 1+ <?php
2+
3+ /**
4+ * 没有考虑hash码冲突的情况
5+ * Created by PhpStorm.
6+ * Author: evolution
7+ * Date: 16-7-8
8+ * Time: 上午9:33
9+ *
10+ * license GPL
11+ */
12+ class HashTable
13+ {
14+ //hashtable size
15+ private $ size = 10 ;
16+ private $ buckets ;
17+
18+ /**
19+ * 初始化hash表
20+ */
21+ public function __construct (){
22+ $ this ->buckets = new SplFixedArray ($ this ->size );
23+ }
24+
25+ /**
26+ * hash 函数
27+ *
28+ * @author: jichao.wang <[email protected] > 29+ *
30+ * @param $key
31+ *
32+ * @return int
33+ */
34+ private function hashFunc ($ key ){
35+ // $len = strlen($key);
36+ // $sum = 0;
37+ // for($i=0; $i<$len; $i++){
38+ // $sum += ord($key[$i]);
39+ // }
40+
41+ $ sum = crc32 ($ key );
42+ echo $ sum ."\r\n" ;
43+ return $ sum % $ this ->size ;
44+ }
45+
46+ /**
47+ * 添加元素到hash表中
48+ *
49+ * @author: jichao.wang <[email protected] > 50+ *
51+ * @param $key
52+ * @param $value
53+ */
54+ public function add ($ key , $ value ){
55+ $ index = $ this ->hashFunc ($ key );
56+ $ this ->buckets [$ index ] = $ value ;
57+ return true ;
58+ }
59+
60+ /**
61+ * 查找元素
62+ * @author: jichao.wang <[email protected] > 63+ *
64+ * @param $key
65+ */
66+ public function find ($ key ){
67+ $ index = $ this ->hashFunc ($ key );
68+ if (isset ($ this ->buckets [$ index ])){
69+ return $ this ->buckets [$ index ];
70+ }
71+
72+ return NULL ;
73+ }
74+
75+ /**
76+ * 获取hashTable中的所有元素
77+ *
78+ * @author: jichao.wang <[email protected] > 79+ * @return mixed
80+ */
81+ public function findAll (){
82+ return $ this ->buckets ;
83+ }
84+
85+ }
Original file line number Diff line number Diff line change 1+ <?php
2+ /**
3+ * Created by PhpStorm.
4+ * Author: evolution
5+ * Date: 16-7-8
6+ * Time: 上午10:52
7+ *
8+ * license GPL
9+ */
10+
11+ include_once "HashTable.php " ;
12+ $ ht = new HashTable ();
13+ $ ht ->add ('name ' ,'wjc ' );
14+ $ ht ->add ('anme ' ,'wjc ' );
15+ $ ht ->add ('anem ' ,'wjc ' );
16+ $ ht ->add ('name1 ' ,'lisi ' );
17+ $ ht ->add ('age ' ,26 );
18+ print_r ($ ht ->findAll ());
19+ echo $ ht ->find ('name ' )."\r\n" ;
20+ echo $ ht ->find ('age ' )."\r\n" ;
You can’t perform that action at this time.
0 commit comments