Java数据结构和算法:哈希表
哈希表是一种数据结构,它可以提供快速的插入操作和查找操作。
哈希表的缺点:基于数组,数组创建后难于扩展。不能有序遍历
哈希化
把关键字转换成数组下标(哈希函数)
冲突(碰撞)
开放地址法
线性探测
// hash.java
// demonstrates hash table with linear probing
// to run this program: C:>java HashTableApp
import java.io.*;
class DataItem{ // (could have more data)private int iData; // data item (key)
//--------------------------------------------------------------public DataItem(int ii) // constructor{ iData = ii; }
//--------------------------------------------------------------public int getKey(){ return iData; }
//--------------------------------------------------------------} // end class DataItem
class HashTable{private DataItem[] hashArray; // array holds hash tableprivate int arraySize;private DataItem nonItem; // for deleted items
// -------------------------------------------------------------public HashTable(int size) // constructor{arraySize = size;hashArray = new DataItem[arraySize];nonItem = new DataItem(-1); // deleted item key is -1}
// -------------------------------------------------------------public void displayTable(){System.out.print("Table: ");for(int j=0; j<arraySize; j++){if(hashArray[j] != null)System.out.print(hashArray[j].getKey() + " ");elseSystem.out.print("** ");}System.out.println("");}
// -------------------------------------------------------------public int hashFunc(int key){return key % arraySize; // hash function}
// -------------------------------------------------------------public void insert(DataItem item) // insert a DataItem// (assumes table not full){int key = item.getKey(); // extract keyint hashVal = hashFunc(key); // hash the key// until empty cell or -1,while(hashArray[hashVal] != null &&hashArray[hashVal].getKey() != -1){++hashVal; // go to next cellhashVal %= arraySize; // wraparound if necessary}hashArray[hashVal] = item; // insert item} // end insert()
// -------------------------------------------------------------public DataItem delete(int key) // delete a DataItem{int hashVal = hashFunc(key); // hash the keywhile(hashArray[hashVal] != null) // until empty cell,{ // found the key?if(hashArray[hashVal].getKey() == key){DataItem temp = hashArray[hashVal]; // save itemhashArray[hashVal] = nonItem; // delete itemreturn temp; // return item}++hashVal; // go to next cellhashVal %= arraySize; // wraparound if necessary}return null; // can't find item} // end delete()
// -------------------------------------------------------------public DataItem find(int key) // find item with key{int hashVal = hashFunc(key); // hash the keywhile(hashArray[hashVal] != null) // until empty cell,{ // found the key?if(hashArray[hashVal].getKey() == key)return hashArray[hashVal]; // yes, return item++hashVal; // go to next cellhashVal %= arraySize; // wraparound if necessary}return null; // can't find item}
// -------------------------------------------------------------} // end class HashTable
class HashTableApp{public static void main(String[] args) throws IOException{DataItem aDataItem;int aKey, size, n, keysPerCell;// get sizesSystem.out.print("Enter size of hash table: ");size = getInt();System.out.print("Enter initial number of items: ");n = getInt();keysPerCell = 10;// make tableHashTable theHashTable = new HashTable(size);for(int j=0; j<n; j++) // insert data{aKey = (int)(java.lang.Math.random() *keysPerCell * size);aDataItem = new DataItem(aKey);theHashTable.insert(aDataItem);}while(true) // interact with user{System.out.print("Enter first letter of ");System.out.print("show, insert, delete, or find: ");char choice = getChar();switch(choice){case 's':theHashTable.displayTable();break;case 'i':System.out.print("Enter key value to insert: ");aKey = getInt();aDataItem = new DataItem(aKey);theHashTable.insert(aDataItem);break;case 'd':System.out.print("Enter key value to delete: ");aKey = getInt();theHashTable.delete(aKey);break;case 'f':System.out.print("Enter key value to find: ");aKey = getInt();aDataItem = theHashTable.find(aKey);if(aDataItem != null){System.out.println("Found " + aKey);}elseSystem.out.println("Could not find " + aKey);break;default:System.out.print("Invalid entry\n");} // end switch} // end while} // end main()
//--------------------------------------------------------------public static String getString() throws IOException{InputStreamReader isr = new InputStreamReader(System.in);BufferedReader br = new BufferedReader(isr);String s = br.readLine();return s;}
//--------------------------------------------------------------public static char getChar() throws IOException{String s = getString();return s.charAt(0);}
//-------------------------------------------------------------public static int getInt() throws IOException{String s = getString();return Integer.parseInt(s);}
//--------------------------------------------------------------} // end class HashTableApp
扩展数组
二次探测
双重散列/二次哈希
// hashDouble.java
// demonstrates hash table with double hashing
// to run this program: C:>java HashDoubleApp
import java.io.*;
class DataItem{ // (could have more items)private int iData; // data item (key)
//--------------------------------------------------------------public DataItem(int ii) // constructor{ iData = ii; }
//--------------------------------------------------------------public int getKey(){ return iData; }
//--------------------------------------------------------------} // end class DataItem
class HashTable{private DataItem[] hashArray; // array is the hash tableprivate int arraySize;private DataItem nonItem; // for deleted items
// -------------------------------------------------------------HashTable(int size) // constructor{arraySize = size;hashArray = new DataItem[arraySize];nonItem = new DataItem(-1);}
// -------------------------------------------------------------public void displayTable(){System.out.print("Table: ");for(int j=0; j<arraySize; j++){if(hashArray[j] != null)System.out.print(hashArray[j].getKey()+ " ");elseSystem.out.print("** ");}System.out.println("");}
// -------------------------------------------------------------public int hashFunc1(int key){return key % arraySize;}
// -------------------------------------------------------------public int hashFunc2(int key){// non-zero, less than array size, different from hF1// array size must be relatively prime to 5, 4, 3, and 2return 5 - key % 5;}
// -------------------------------------------------------------// insert a DataItempublic void insert(int key, DataItem item)// (assumes table not full){int hashVal = hashFunc1(key); // hash the keyint stepSize = hashFunc2(key); // get step size// until empty cell or -1while(hashArray[hashVal] != null &&hashArray[hashVal].getKey() != -1){hashVal += stepSize; // add the stephashVal %= arraySize; // for wraparound}hashArray[hashVal] = item; // insert item} // end insert()
// -------------------------------------------------------------public DataItem delete(int key) // delete a DataItem{int hashVal = hashFunc1(key); // hash the keyint stepSize = hashFunc2(key); // get step sizewhile(hashArray[hashVal] != null) // until empty cell,{ // is correct hashVal?if(hashArray[hashVal].getKey() == key){DataItem temp = hashArray[hashVal]; // save itemhashArray[hashVal] = nonItem; // delete itemreturn temp; // return item}hashVal += stepSize; // add the stephashVal %= arraySize; // for wraparound}return null; // can't find item} // end delete()
// -------------------------------------------------------------public DataItem find(int key) // find item with key// (assumes table not full){int hashVal = hashFunc1(key); // hash the keyint stepSize = hashFunc2(key); // get step sizewhile(hashArray[hashVal] != null) // until empty cell,{ // is correct hashVal?if(hashArray[hashVal].getKey() == key)return hashArray[hashVal]; // yes, return itemhashVal += stepSize; // add the stephashVal %= arraySize; // for wraparound}return null; // can't find item}
// -------------------------------------------------------------} // end class HashTable
class HashDoubleApp{public static void main(String[] args) throws IOException{int aKey;DataItem aDataItem;int size, n;// get sizesSystem.out.print("Enter size of hash table: ");size = getInt();System.out.print("Enter initial number of items: ");n = getInt();// make tableHashTable theHashTable = new HashTable(size);for(int j=0; j<n; j++) // insert data{aKey = (int)(java.lang.Math.random() * 2 * size);aDataItem = new DataItem(aKey);theHashTable.insert(aKey, aDataItem);}while(true) // interact with user{System.out.print("Enter first letter of ");System.out.print("show, insert, delete, or find: ");char choice = getChar();switch(choice){case 's':theHashTable.displayTable();break;case 'i':System.out.print("Enter key value to insert: ");aKey = getInt();aDataItem = new DataItem(aKey);theHashTable.insert(aKey, aDataItem);break;case 'd':System.out.print("Enter key value to delete: ");aKey = getInt();theHashTable.delete(aKey);break;case 'f':System.out.print("Enter key value to find: ");aKey = getInt();aDataItem = theHashTable.find(aKey);if(aDataItem != null)System.out.println("Found " + aKey);elseSystem.out.println("Could not find " + aKey);break;default:System.out.print("Invalid entry\n");} // end switch} // end while} // end main()
//--------------------------------------------------------------public static String getString() throws IOException{InputStreamReader isr = new InputStreamReader(System.in);BufferedReader br = new BufferedReader(isr);String s = br.readLine();return s;}
//--------------------------------------------------------------public static char getChar() throws IOException{String s = getString();return s.charAt(0);}
//-------------------------------------------------------------public static int getInt() throws IOException{String s = getString();return Integer.parseInt(s);}
//--------------------------------------------------------------} // end class HashDoubleApp
链地址法
数组 + 链表,桶结构
装载因子
// hashChain.java
// demonstrates hash table with separate chaining
// to run this program: C:>java HashChainApp
import java.io.*;
class Link{ // (could be other items)private int iData; // data itempublic Link next; // next link in list
// -------------------------------------------------------------public Link(int it) // constructor{ iData= it; }
// -------------------------------------------------------------public int getKey(){ return iData; }
// -------------------------------------------------------------public void displayLink() // display this link{ System.out.print(iData + " "); }} // end class Link
class SortedList{private Link first; // ref to first list item
// -------------------------------------------------------------public void SortedList() // constructor{ first = null; }
// -------------------------------------------------------------public void insert(Link theLink) // insert link, in order{int key = theLink.getKey();Link previous = null; // start at firstLink current = first;// until end of list,while( current != null && key > current.getKey() ){ // or current > key,previous = current;current = current.next; // go to next item}if(previous==null) // if beginning of list,first = theLink; // first --> new linkelse // not at beginning,previous.next = theLink; // prev --> new linktheLink.next = current; // new link --> current} // end insert()
// -------------------------------------------------------------public void delete(int key) // delete link{ // (assumes non-empty list)Link previous = null; // start at firstLink current = first;// until end of list,while( current != null && key != current.getKey() ){ // or key == current,previous = current;current = current.next; // go to next link}// disconnect linkif(previous==null) // if beginning of listfirst = first.next; // delete first linkelse // not at beginningprevious.next = current.next; // delete current link} // end delete()
// -------------------------------------------------------------public Link find(int key) // find link{Link current = first; // start at first// until end of list,while(current != null && current.getKey() <= key){ // or key too small,if(current.getKey() == key) // is this the link?return current; // found it, return linkcurrent = current.next; // go to next item}return null; // didn't find it} // end find()
// -------------------------------------------------------------public void displayList(){System.out.print("List (first-->last): ");Link current = first; // start at beginning of listwhile(current != null) // until end of list,{current.displayLink(); // print datacurrent = current.next; // move to next link}System.out.println("");}} // end class SortedList
class HashTable{private SortedList[] hashArray; // array of listsprivate int arraySize;
// -------------------------------------------------------------public HashTable(int size) // constructor{arraySize = size;hashArray = new SortedList[arraySize]; // create arrayfor(int j=0; j<arraySize; j++) // fill arrayhashArray[j] = new SortedList(); // with lists}
// -------------------------------------------------------------public void displayTable(){for(int j=0; j<arraySize; j++) // for each cell,{System.out.print(j + ". "); // display cell numberhashArray[j].displayList(); // display list}}
// -------------------------------------------------------------public int hashFunc(int key) // hash function{return key % arraySize;}
// -------------------------------------------------------------public void insert(Link theLink) // insert a link{int key = theLink.getKey();int hashVal = hashFunc(key); // hash the keyhashArray[hashVal].insert(theLink); // insert at hashVal} // end insert()
// -------------------------------------------------------------public void delete(int key) // delete a link{int hashVal = hashFunc(key); // hash the keyhashArray[hashVal].delete(key); // delete link} // end delete()
// -------------------------------------------------------------public Link find(int key) // find link{int hashVal = hashFunc(key); // hash the keyLink theLink = hashArray[hashVal].find(key); // get linkreturn theLink; // return link}
// -------------------------------------------------------------} // end class HashTable
class HashChainApp{public static void main(String[] args) throws IOException{int aKey;Link aDataItem;int size, n, keysPerCell = 100;// get sizesSystem.out.print("Enter size of hash table: ");size = getInt();System.out.print("Enter initial number of items: ");n = getInt();// make tableHashTable theHashTable = new HashTable(size);for(int j=0; j<n; j++) // insert data{aKey = (int)(java.lang.Math.random() *keysPerCell * size);aDataItem = new Link(aKey);theHashTable.insert(aDataItem);}while(true) // interact with user{System.out.print("Enter first letter of ");System.out.print("show, insert, delete, or find: ");char choice = getChar();switch(choice){case 's':theHashTable.displayTable();break;case 'i':System.out.print("Enter key value to insert: ");aKey = getInt();aDataItem = new Link(aKey);theHashTable.insert(aDataItem);break;case 'd':System.out.print("Enter key value to delete: ");aKey = getInt();theHashTable.delete(aKey);break;case 'f':System.out.print("Enter key value to find: ");aKey = getInt();aDataItem = theHashTable.find(aKey);if(aDataItem != null)System.out.println("Found " + aKey);elseSystem.out.println("Could not find " + aKey);break;default:System.out.print("Invalid entry\n");} // end switch} // end while} // end main()
//--------------------------------------------------------------public static String getString() throws IOException{InputStreamReader isr = new InputStreamReader(System.in);BufferedReader br = new BufferedReader(isr);String s = br.readLine();return s;}
//-------------------------------------------------------------public static char getChar() throws IOException{String s = getString();return s.charAt(0);}
//-------------------------------------------------------------public static int getInt() throws IOException{String s = getString();return Integer.parseInt(s);}
//--------------------------------------------------------------} // end class HashChainApp
哈希函数
快速的计算
随机的关键字
使用质数作为取模的基数
Java数据结构和算法:哈希表相关推荐
- java数据结构与算法之顺序表与链表深入分析
转载请注明出处(万分感谢!): http://blog.csdn.net/javazejian/article/details/52953190 出自[zejian的博客] 关联文章: java数据结 ...
- 数据结构与算法——哈希表
哈希表 看一个实际需求,google公司的一个上机题: 有一个公司,当有新的员工来报道时,要求将该员工的信息加入(id,性别,年龄,住址-)当输入该员工的id时,要求查找到该员工的所有信息. 要求: ...
- 数据结构与算法——哈希表与字符串
文章目录 1.预备知识 1.1 最简单的哈希--统计字符个数 1.2 哈希表排序整数 1.3 哈希映射的问题 2.最长回文串 2.1 题目描述 2.2 C++代码实现 3.单词规律 3.1 题目描述 ...
- python hash表_python数据结构与算法——哈希表
哈希表 学习笔记 参考翻译自:<复杂性思考> 及对应的online版本:http://greenteapress.com/complexity/html/thinkcomplexity00 ...
- 【python】数据结构与算法—哈希表
一.哈希表 用顺序表来存数据 存键值对时,通过哈希函数计算出键对应的索引,将值存到索引对应的数据区中 获取数据时,通过哈希函数计算出键对应的索引,将该索引对应的数据取出来 二.哈希冲突 对于任何哈希函 ...
- Java数据结构与算法解析(一)——表
本节我们讨论常见常用的数据结构--表. 如果要通俗简单的说什么是表,那我们可以这样说:按顺序排好的元素集合就是表. 表的概述 抽象数据类型是带有一组操作的一些对象的结合 1.定义: 线性表是一个线性结 ...
- Java数据结构和算法:线性表
线性表的定义 线性表(linear-list)是最常用最简单的一种数据结构.一个线性表是n (n≥0)个相同类型数据元素的有限序列.记为: L= (a1, a2 , - , an ). 其中,L是表名 ...
- Java数据结构与算法_线性表_顺序表与链表
文章目录 线性表 顺序表 顺序表API设计 顺序表的代码实现 链表 单向链表 双向链表 总结 线性表 概述 线性表是最基本.最简单.也是最常用的一种数据结构. 一个线性表是n个具有相同特性的数据元素的 ...
- java数据结构与算法之双链表设计与实现
转载请注明出处(万分感谢!): http://blog.csdn.net/javazejian/article/details/53047590 出自[zejian的博客] 关联文章: java数据结 ...
- java数据结构与算法之(Queue)队列设计与实现
[版权申明]转载请注明出处(请尊重原创,博主保留追究权) http://blog.csdn.net/javazejian/article/details/53375004 出自[zejian的博客] ...
最新文章
- OpenCV学习笔记2---命名规约
- 29、Power Query-分支语句的进阶
- MySQL / 多版本并发控制
- Java—简单的图书管理系统
- html复选框值改变后事件,javascript – 从onclick/onchange事件获取HTML值的复选框
- 计算机网络利用率是什么_当我们在谈论高并发的时候究竟在谈什么?
- Linux 系统服务漏洞PwnKit 已存在12年,可获得所有主流发布版本的root 权限
- 装个discuz论坛
- 2015.12.24 OC中的装箱
- R_ggplot2基础(四)
- Java多线程为什么使用while循环来调用wait方法
- 实际运用中DataSet、DataTable、DataRow点滴
- MongoDB学习笔记(查询)
- TensorFlow是什么
- 2016php开发 饱和了吗,2016PHP程序员待遇和就业前景调查
- Mapbox3D特效(立体闪光墙)
- HTTPS/数字证书/数字签名
- 【粉丝福利,限时免费】【千里之行,始于脚下】我在CSDN上的精品博文汇总,收藏起来慢慢看
- C语言基础:函数的声明与定义
- MAPJOIN来解决实际的问题