1 / 60

Introduction to Hashing: Efficient Data Storage and Retrieval

Learn the concepts of hashing and how it can be used for fast insertion, deletion, and retrieval of data. Understand hash functions and collision resolution techniques like separate chaining. Suitable for those familiar with data structures like lists, stacks, queues, BST, and AVL trees.

pdick
Télécharger la présentation

Introduction to Hashing: Efficient Data Storage and Retrieval

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. Hashing Vishnu Kotrajaras, PhD Nattee Niparnan, PhD

  2. Flashback Still recall something before midterm?

  3. Recall the previous ADT • List, Stack, Queue • BST • AVL • We wish to do Insert, Delete and Find

  4. Do we happy with AVL tree? • We want something FASTER!!! • Possible with “hashing”

  5. Overview What is hash?

  6. Hashing property • Insert O(1) • Delete O(1) • Find O(1) • Lacks order, traversal

  7. Hashing Idea • What happen if all possible data is the date of the month? • Post Office analogy • Addressing!!!

  8. Hash Table • Table (storage) • Key (address) • And possibly the Value (things to store)

  9. Realization of Hash Table Put it into a practical use

  10. What is the problem? • What if the data is not only 1 – 31? • What if the data is not a number ?

  11. Hash function • Mash key into something else

  12. Hash function • We use it to try to distribute values evenly throughout our table. We may use: • Key number% tableSize • But if tableSize is 10, 20, 30, …we cannot use this function. • What if keys are Strings? • Let’s see some example.

  13. Hash function (1st example) • Sum theASCII values of all alphabets public static int hash(String key, int tableSize){ int hashVal = 0; for(int i =0; i<key.length(); i++) hashVal += key.charAt(i); return hashVal%tableSize; }

  14. The method in the last page is not good if the table is large: • Whet if each key is short (e.g. 8 alphabets?) • An ASCII normally has a maximum value of 127. • Therefore the sum of all 8 alphabets will not exceed 127*8. • If the table is big, data will not be distributed evenly. The 10,000th member Indices will concentrate at the front.

  15. Hash function (2nd example) • Assume we have a big table, and each key is made from at least 3 random alphabets. • We look at the first 3 alphabets only. public static int hash(String key, int tableSize){ return (key.charAt(0) +27*key.charAt(1) +729* key.charAT(2))%tableSize; } 27*27 All alphabets, including space This distributes well in a table of size 10000. (10007is the first prime after 10000, we will use this number. You will see why).

  16. Wait, any actual key will never be random like this: • There will be a lot of repetition.

  17. Hash function (3rd example) • We calculate apolynomial function of 37, usingHorner’s Rule. • We can calculatek0 + 37k1+ 37*37k2 by using [(k2*37)+k1]*37 +k0 Horner rule is to repeat this -> n times. In fact, it is a calculation of:

  18. public static int hash(String key, int tableSize){ int hashVal = 0; for(int i =0; i<key.length(); i++) hashVal= 37*hashVal+key.charAt(i); hashVal %= tableSize; if(hashVal<0) hashVal += tableSize; return hashVal; } Possible overflow

  19. What is “GOOD” hash function? • Low cost • Determinism • Uniformity • Variable Range • Injective • Perfect hash function?

  20. Side Note eMule, BitTorrent, all P2P MD5

  21. Still More Problem Collision

  22. Collision Resolution • Separate Chaining • Toolbox analogy • Open addressing • Library shelf analogy

  23. Separate Chaining • Try to put it into the same position • Use another “Data Structure”

  24. Fixing collision:separate chaining • Store repeated elements in a linked list. • If you want to search for an element, use hash function, then search in the list given by that hash function. • If you want to insert an element, • use hash function to find a list to put that element in. • After that, check the list to see whether it already contains the element. If the list does not have that element then insert the element at the front. • Statistically, a newly inserted element is often accessed again soon after the insertion.

  25. Code for an object that has a hash function. • public interface Hashable • { • /** • * Compute a hash function for this object. • * @param tableSize the hash table size. • * @return (deterministically) a number between • * 0 and tableSize-1, distributed equitably. • */ • int hash( int tableSize ); • }

  26. How we use a Hashable object. Public class Student implements Hashable{ private String name; private double number; private int year; public int hash(int tableSize){ return SeparateChainingHashTable.hash(name, tableSize); } public boolean equals(Object rhs){ return name.equals(((Student)rhs).name); } } static method from our HashTable class.

  27. public class SeparateChainingHashTable • { • /** • * Construct the hash table. • */ • public SeparateChainingHashTable( ) • { • this( DEFAULT_TABLE_SIZE ); • } • /** • * Construct the hash table. • * @param size approximate table size. • */ • public SeparateChainingHashTable( int size ) • { • theLists = new LinkedList[ nextPrime( size ) ]; • for( int i = 0; i < theLists.length; i++ ) • theLists[ i ] = new LinkedList( ); • }

  28. We use Student here • /** • * Insert into the hash table. If the item is • * already present, then do nothing. • * @param x the item to insert. • */ • public void insert( Hashable x ) • { • LinkedList whichList = theLists[ x.hash( theLists.length ) ]; • LinkedListItr itr = whichList.find( x ); • if( itr.isPastEnd( ) ) • whichList.insert( x, whichList.zeroth( ) ); • } • /** • * Remove from the hash table. • * @param x the item to remove. • */ • public void remove( Hashable x ) • { • theLists[ x.hash( theLists.length ) ].remove( x ); • }

  29. /** • * Find an item in the hash table. • * @param x the item to search for. • * @return the matching item, or null if not found. • */ • public Hashable find( Hashable x ) • { • return (Hashable)theLists[ x.hash( theLists.length ) ].find( x ).retrieve( ); • } • /** • * Make the hash table logically empty. • */ • public void makeEmpty( ) • { • for( int i = 0; i < theLists.length; i++ ) • theLists[ i ].makeEmpty( ); • }

  30. /** • * A hash routine for String objects. • * @param key the String to hash. • * @param tableSize the size of the hash table. • * @return the hash value. • */ • public static int hash( String key, int tableSize ) • { • int hashVal = 0; • for( int i = 0; i < key.length( ); i++ ) • hashVal = 37 * hashVal + key.charAt( i ); • hashVal %= tableSize; • if( hashVal < 0 ) • hashVal += tableSize; • return hashVal; • }

  31. private static final int DEFAULT_TABLE_SIZE = 101; • /** The array of Lists. */ • private LinkedList [ ] theLists; • /** • * Internal method to find a prime number at least as large as n. • * @param n the starting number (must be positive). • * @return a prime number larger than or equal to n. • */ • private static int nextPrime( int n ) • { • if( n % 2 == 0 ) • n++; • for( ; !isPrime( n ); n += 2 ) • ; • return n; • }

  32. /** • * Internal method to test if a number is prime. • * Not an efficient algorithm. • * @param n the number to test. • * @return the result of the test. • */ • private static boolean isPrime( int n ) • { • if( n == 2 || n == 3 ) • return true; • if( n == 1 || n % 2 == 0 ) • return false; • for( int i = 3; i * i <= n; i += 2 ) • if( n % i == 0 ) • return false; • return true; • }

  33. // Simple main • public static void main( String [ ] args ) • { • SeparateChainingHashTable H = new SeparateChainingHashTable( ); • final int NUMS = 4000; • final int GAP = 37; • System.out.println( "Checking... (no more output means success)" ); • for( int i = GAP; i != 0; i = ( i + GAP ) % NUMS ) • H.insert( new MyInteger( i ) ); • for( int i = 1; i < NUMS; i+= 2 ) • H.remove( new MyInteger( i ) ); • for( int i = 2; i < NUMS; i+=2 ) • if( ((MyInteger)(H.find( new MyInteger( i ) ))).intValue( ) != i ) • System.out.println( "Find fails " + i ); • for( int i = 1; i < NUMS; i+=2 ) • { • if( H.find( new MyInteger( i ) ) != null ) • System.out.println( "OOPS!!! " + i ); • } • } • }

  34. Separate Chaining : More variation • Can we use BST instead? • AVL? • B-Tree?

  35. Some Analysis • Load factor • It is an average length of linked list. Search time = time to do hashing + time to search list = constant + time to search list • Unsuccessful search Search time == average list length==load factor

  36. Successful search • In a list that we will search, there is one node that contains an object that we want to find. There are other nodes too (0 or more). • in a table, if we have N members, distributed into M lists. • There are N-1 nodes that do not have what we want. • If we distribute these nodes evenly among the lists. Each list will have(N-1)/M nodes. • = lambda- (1/M) • = lambda, because M is large. • On average, half the list will be searched before we find what we want. That is,lambda/2 steps will be executed. • Therefore the average time to find the required element is 1 + (lambda/2) steps. • The tableSize is not important. What really matters is the load factor.

  37. Open Addressing • Try to use another slot • “Probing” • Try h0(x), h1(x), … • hi(x)=[hash(x)+f(i)]%tableSize, f(0)=0 • “i” is the collision count • Use no extra space • Load factor is very important

  38. Open Addressing Technique • Linear probing • Quadratic probing • Double hashing

  39. Fixing collision by using Open addressing • No list. • If there is a collision, then keep calculating a new index until an empty slot is found. • The new index is at h0(x), h1(x), … • hi(x)=[hash(x)+f(i)]%tableSize, f(0)=0 • Every data must be put into our table. Therefore the table must be large enough to distribute data. • Load factor <=0.5

  40. Open addressing: linear probing • F is a linear function of i. • Normally we have -> f(i)=i • It is “looking ahead one slot at a time.” • This may take time. There will be consecutive filled slots, called primary clustering. If a new collision takes place, it will take some time before we can find another empty slot.

  41. Open addressing: quadratic probing • There is noprimary clustering by this method. • We usually have -> f(i)=i2 • hi(x)=[hash(x)+f(i)]%tableSize a ifb collides with a, we add 12 to find a new empty slot. If c also collides with a, we add 12 to find b. We need to go further by adding 22 instead.

  42. However, if our table is more than half full or the tableSize is not prime, this method does not guarantee an empty slot. • Butif the table is not yet half full and the tableSize is prime, it is proven that we can always find an empty slot for a new value.

  43. Proof • Let the tableSize be a prime number greater than 3. • Let (h(x)+i2) mod tableSize • (h(x)+j2) mod tableSize • Prove by contradiction • Assume both positions are the same and i !=j. Be 2 empty slot positions.

  44. i-j =0 is impossible because we assumed they are not equal. • i+j=0 is also impossible, • Therefore our assumption that the two positions are the same is wrong. • Thus the two positions are always different. • So there is always a slot for a new value, if the table is not yet half full and the tableSize is prime.

  45. Why prime? • If not, the number of available slots will greatly reduce. • Example: tableSize == 16. Assume a normal hashing gives index ==0. (quadratic probing) 32 22 12 42 72 62 52 You can see that they fall in the same positions.

  46. Deleting in open addressing

  47. Open addressing implementation class HashEntry { Hashable element; // the element boolean isActive; // false means -> deleted public HashEntry( Hashable e ){ this( e, true ); } public HashEntry( Hashable e, boolean i ){ element = e; isActive = i; } }

  48. public class QuadraticProbingHashTable{ • private static final int DEFAULT_TABLE_SIZE = 11; • /** The array of elements. */ • private HashEntry [ ] array; // The array of elements • private int currentSize; // The number of occupied cells • public QuadraticProbingHashTable( ){ • this( DEFAULT_TABLE_SIZE ); • } • /** • * Construct the hash table. • * @param size the approximate initial size. • */ • public QuadraticProbingHashTable( int size ){ • allocateArray( size ); • makeEmpty( ); • } nonactive null active

  49. /** • * Internal method to allocate array. • * @param arraySize the size of the array. • */ • private void allocateArray( int arraySize ){ • array = new HashEntry[ arraySize ]; • } • /** • * Make the hash table logically empty. • */ • public void makeEmpty( ){ • currentSize = 0; • for( int i = 0; i < array.length; i++ ) • array[ i ] = null; • }

  50. /** • * Return true if currentPos exists and is active. • * @param currentPos the result of a call to findPos. • * @return true if currentPos is active. • */ • private boolean isActive( int currentPos ){ • return array[ currentPos ] != null && array[ currentPos ].isActive; • }

More Related