HashTable(分离链接法)简单实现

来源:互联网 发布:用spss怎么输入数据 编辑:程序博客网 时间:2024/04/29 13:12

散列表的实现通常叫做散列hashing。散列是一种用于以常数平均时间执行插入、删除和查找的技术。但是,那些需要元素间任何排序信息的树操作将不会得到有效的支持。理想的散列表数据结构只不过是一个包含一些项的具有固定大小的数组。通常查找是对项的某个部分(数据域)进行的,这部分叫做关键字。例如,项可以由一个串(作为关键字)和其它一些数据域组成。我们把表的大小记作TableSize,并将其理解为散列数据结构的一部分,而不仅仅是浮动于全局的的某个变量。通常习惯是让表从0到TableSize-1变化。

    每个关键字被映射到从0到TableSize-1这个范围中的某个数,并且被放到适当的单元中。这个映射就叫做散列函数,理想情况下它应该计算起来简单,并且应该保证任何两个不同的关键字映射到不同的单元。不过,这是不可能的,因为单元的数目是有限的,而关键字实际上是用不完的。因此,我们寻找一个散列函数,该函数要在单元之间均匀地分配关键字。

    这就是散列的基本想法,剩下的问题就是要选择一个函数,决定当两个关键字散列到同一个值得时候(即发生冲突)应该做什么以及如何确定散列表的大小。

  • 散列函数
    如果输入的关键字是整数,则一般合理的方法就是直接返回Key mod TableSize,除非Key碰巧具有某些不合乎需要的性质。在这种情况下,散列函数的选择需要仔细地考虑。例如,若表的大小是10而关键字都以0位个位,则此时上述标准的散列函数就不太好。为了避免上面的情况,好的方法通常是保证表的大小是素数。当输入的关键字是随机整数时,散列函数不仅计算起来简单而且关键字的分配也很均匀。
    通常,关键字是字符串,在这种情况下,散列函数需要仔细地选择。剩下的主要编程细节是解决冲突的消除问题。如果当一个元素被插入时与一个已经插入的元素散列到相同的值,那么就产生一个冲突,这个冲突需要消除。解决这种冲突的方法有几种,这里主要介绍分离链接法、开放定址法。
  • 分离链接法
分离链状法是将散列到同一个值的所有元素保留到一个表中。我们可以使用标准库表的实现方法。如果空间很紧,则更可取的方法是避免使用它们(因为这些表是双向链接的并且浪费空间)。为执行一次查找,我们使用散列函数来确定究竟遍历哪个链表,然后我们再在相应的链表中查看该元素是否已在适当的位置(如果允许插入重复元,那么通常要留出一个额外的域,这个域当出现匹配事件时增1)。如果这个元素是个新元素,那么它将被插入到链表的前端,这不仅因为方便,还因为常常发生这样的事:新插入的元素最有可能不久又被访问。
    我们定义散列表的装填因子 λ为散列表中的元素个数对该表大小的比。执行一次查找所需要的工作是计算散列函数值所需要的常数时间加上遍历链表所用的时间。再一次不成功的查找中,要考察的节点数平均为λ。一次成功的查找则平均需要遍历大约1+(λ/2)个链。分析指出,散列表的大小实际上并不需要,而装填因子才是重要的。分离链状法的一般法则是是的表的大小与预料的元素个数大致相等,即λ≈1。
    以下就是一个用分离链接法简单实现的散列表:
[java] view plain copy
  1. import java.util.Iterator;  
  2. import java.util.LinkedList;  
  3. import java.util.List;  
  4. import java.util.Random;  
  5.   
  6. public class SeparateChainingHashTable<AnyType> {  
  7.     private static final int DEFAULT_TABLE_SIZE = 10;//默认容量  
  8.     private List<AnyType>[] theLists;//散列表的数组  
  9.     private int currentSize;//当前数据个数  
  10.   
  11.     public SeparateChainingHashTable() {  
  12.         this(DEFAULT_TABLE_SIZE);  
  13.     }  
  14.   
  15.     public SeparateChainingHashTable(int size) {  
  16.         theLists = new LinkedList[nextPrime(size)];  
  17.         for (int i = 0; i < theLists.length; i++) {  
  18.             theLists[i] = new LinkedList<AnyType>();  
  19.         }  
  20.     }  
  21.   
  22.     /** 
  23.      * 使哈希表变空 
  24.      */  
  25.     public void makeEmpty() {  
  26.         for (List<AnyType> list : theLists) {  
  27.             list.clear();  
  28.         }  
  29.         currentSize = 0;  
  30.     }  
  31.   
  32.     /** 
  33.      * 哈希表是否包含某元素 
  34.      * @param x 查询元素 
  35.      * @return 查询结果 
  36.      */  
  37.     public boolean contains(AnyType x) {  
  38.         List<AnyType> whichList = theLists[myhash(x)];  
  39.         return whichList.contains(x);  
  40.     }  
  41.   
  42.     /** 
  43.      * 向哈希表中插入某元素,若存在则不操作 
  44.      * @param x 插入元素 
  45.      */  
  46.     public void insert(AnyType x) {  
  47.         List<AnyType> whichList = theLists[myhash(x)];  
  48.         if (!whichList.contains(x)) {  
  49.             whichList.add(x);  
  50.             if (++currentSize > theLists.length) {  
  51.                 rehash();  
  52.             }  
  53.         } else {  
  54.         }  
  55.     }  
  56.   
  57.     /** 
  58.      * 向哈希表中删除某元素,若不存在则不操作 
  59.      * @param x 删除元素 
  60.      */  
  61.     public void remove(AnyType x) {  
  62.         List<AnyType> whichList = theLists[myhash(x)];  
  63.         if (whichList.contains(x)) {  
  64.             whichList.remove(x);  
  65.             currentSize--;  
  66.         } else {  
  67.         }  
  68.     }  
  69.   
  70.     /** 
  71.      * 哈希算法,有多种实现方法 
  72.      * @param x 元素 
  73.      * @return 哈希值 
  74.      */  
  75.     private int myhash(AnyType x) {  
  76.         int hashVal = x.hashCode();  
  77.         hashVal %= theLists.length;  
  78.         if (hashVal < 0) {  
  79.             hashVal += theLists.length;  
  80.         }  
  81.         return hashVal;  
  82.     }  
  83.   
  84.     /** 
  85.      * 再散列函数,插入空间不够时执行 
  86.      */  
  87.     private void rehash() {  
  88.         List<AnyType>[] oldLists = theLists;  
  89.         // 分配一个两倍大小的空表  
  90.         theLists = new List[nextPrime(2 * theLists.length)];  
  91.         for(int j=0;j<theLists.length;j++){  
  92.             theLists[j]=new LinkedList<AnyType>();  
  93.         }  
  94.         currentSize = 0;  
  95.         for (int i = 0; i < oldLists.length; i++) {  
  96.             for (AnyType item : oldLists[i]) {  
  97.                 insert(item);  
  98.             }  
  99.         }  
  100.     }  
  101.   
  102.     /** 
  103.      * 检查某整数是否为素数 
  104.      * @param num 检查整数 
  105.      * @return 检查结果 
  106.      */  
  107.     private static boolean isPrime(int num) {  
  108.         if (num == 2 || num == 3) {  
  109.             return true;  
  110.         }  
  111.         if (num == 1 || num % 2 == 0) {  
  112.             return false;  
  113.         }  
  114.         for (int i = 3; i * i <= num; i += 2) {  
  115.             if (num % i == 0) {  
  116.                 return false;  
  117.             }  
  118.         }  
  119.         return true;  
  120.     }  
  121.   
  122.     /** 
  123.      * 返回不小于某个整数的素数 
  124.      * @param num 整数 
  125.      * @return 下一个素数(可以相等) 
  126.      */  
  127.     private static int nextPrime(int num) {  
  128.         if (num == 0 || num == 1 || num == 2) {  
  129.             return 2;  
  130.         }  
  131.         if (num % 2 == 0) {  
  132.             num++;  
  133.         }  
  134.         while (!isPrime(num)) {  
  135.             num += 2;  
  136.         }  
  137.         return num;  
  138.     }  
  139.   
  140.     /** 
  141.      * 输出散列表 
  142.      */  
  143.     public void printTable() {  
  144.         for(int i=0;i<theLists.length;i++){  
  145.             System.out.println("-----");  
  146.             Iterator iterator=theLists[i].iterator();  
  147.             while(iterator.hasNext()){  
  148.                 System.out.print(iterator.next()+" ");  
  149.             }  
  150.             System.out.println();  
  151.         }  
  152.     }  
  153.   
  154.     public static void main(String[] args) {  
  155.         Random random = new Random();  
  156.         SeparateChainingHashTable<Integer> hashTable = new SeparateChainingHashTable<Integer>();  
  157.         for (int i = 0; i < 30; i++) {  
  158.             hashTable.insert(random.nextInt(30));  
  159.         }  
  160.         hashTable.printTable();  
  161.     }  
  162. }  
0 0