Data Structures Dana Shapira Hash Tables 26/06/07.

Slides:



Advertisements
Similar presentations
Chapter 11. Hash Tables.
Advertisements

Hash Tables.
Hash Tables CIS 606 Spring 2010.
CS 253: Algorithms Chapter 11 Hashing Credit: Dr. George Bebis.
Log Files. O(n) Data Structure Exercises 16.1.
CS Section 600 CS Section 002 Dr. Angela Guercio Spring 2010.
Hashing CS 3358 Data Structures.
Data Structures – LECTURE 11 Hash tables
פעולות מילון Insert, Delete, Search Binary Search Tree, AVL, 2-3 Tree, Skip List O(log n) האם יש מבנה עם סבוכיות (1)O? לא למפתח כלשהו.
Hash Tables How well do hash tables support dynamic set operations? Implementations –Direct address –Hash functions Collision resolution methods –Universal.
11.Hash Tables Hsu, Lih-Hsing. Computer Theory Lab. Chapter 11P Directed-address tables Direct addressing is a simple technique that works well.
© 2006 Pearson Addison-Wesley. All rights reserved13 A-1 Chapter 13 Hash Tables.
Hash Tables1 Part E Hash Tables  
Hashing COMP171 Fall Hashing 2 Hash table * Support the following operations n Find n Insert n Delete. (deletions may be unnecessary in some applications)
Tirgul 9 Hash Tables (continued) Reminder Examples.
Introduction to Hashing CS 311 Winter, Dictionary Structure A dictionary structure has the form: (Key, Data) Dictionary structures are organized.
Tirgul 7. Find an efficient implementation of a dynamic collection of elements with unique keys Supported Operations: Insert, Search and Delete. The keys.
COMP 171 Data Structures and Algorithms Tutorial 10 Hash Tables.
Tirgul 8 Hash Tables (continued) Reminder Examples.
Lecture 10: Search Structures and Hashing
Lecture 11 oct 7 Goals: hashing hash functions chaining closed hashing application of hashing.
Hashing General idea: Get a large array
Data Structures Using C++ 2E Chapter 9 Searching and Hashing Algorithms.
Hashtables David Kauchak cs302 Spring Administrative Talk today at lunch Midterm must take it by Friday at 6pm No assignment over the break.
Spring 2015 Lecture 6: Hash Tables
Symbol Tables Symbol tables are used by compilers to keep track of information about variables functions class names type names temporary variables etc.
Algorithm Course Dr. Aref Rashad February Algorithms Course..... Dr. Aref Rashad Part: 4 Search Algorithms.
Implementing Dictionaries Many applications require a dynamic set that supports dictionary-type operations such as Insert, Delete, and Search. E.g., a.
Data Structures Hash Tables. Hashing Tables l Motivation: symbol tables n A compiler uses a symbol table to relate symbols to associated data u Symbols:
David Luebke 1 10/25/2015 CS 332: Algorithms Skip Lists Hash Tables.
Hash Tables Comp 550.
Hashing Sections 10.2 – 10.3 CS 302 Dr. George Bebis.
Data Structures and Algorithms (AT70. 02) Comp. Sc. and Inf. Mgmt
Hashing Hashing is another method for sorting and searching data.
Hashing Amihood Amir Bar Ilan University Direct Addressing In old days: LD 1,1 LD 2,2 AD 1,2 ST 1,3 Today: C
David Luebke 1 11/26/2015 Hash Tables. David Luebke 2 11/26/2015 Hash Tables ● Motivation: Dictionaries ■ Set of key/value pairs ■ We care about search,
Lecture 12COMPSCI.220.FS.T Symbol Table and Hashing A ( symbol) table is a set of table entries, ( K,V) Each entry contains: –a unique key, K,
1 Hashing - Introduction Dictionary = a dynamic set that supports the operations INSERT, DELETE, SEARCH Dictionary = a dynamic set that supports the operations.
Ihab Mohammed and Safaa Alwajidi. Introduction Hash tables are dictionary structure that store objects with keys and provide very fast access. Hash table.
Hashing Basis Ideas A data structure that allows insertion, deletion and search in O(1) in average. A data structure that allows insertion, deletion and.
Tirgul 11 Notes Hash tables –reminder –examples –some new material.
Introduction to Algorithms 6.046J/18.401J LECTURE7 Hashing I Direct-access tables Resolving collisions by chaining Choosing hash functions Open addressing.
Hashtables. An Abstract data type that supports the following operations: –Insert –Find –Remove Search trees can be used for the same operations but require.
Hashing 1 Hashing. Hashing 2 Hashing … * Again, a (dynamic) set of elements in which we do ‘search’, ‘insert’, and ‘delete’ n Linear ones: lists, stacks,
Midterm Midterm is Wednesday next week ! The quiz contains 5 problems = 50 min + 0 min more –Master Theorem/ Examples –Quicksort/ Mergesort –Binary Heaps.
Chapter 13 C Advanced Implementations of Tables – Hash Tables.
Data Structures Using C++
Hashtables David Kauchak cs302 Spring Administrative Midterm must take it by Friday at 6pm No assignment over the break.
CS6045: Advanced Algorithms Data Structures. Hashing Tables Motivation: symbol tables –A compiler uses a symbol table to relate symbols to associated.
CMSC 341 Hashing Readings: Chapter 5. Announcements Midterm II on Nov 7 Review out Oct 29 HW 5 due Thursday CMSC 341 Hashing 2.
1 Hash Tables Chapter Motivation Many applications require only: –Insert –Search –Delete Examples –Symbol tables –Memory management mechanisms.
CSC 413/513: Intro to Algorithms Hash Tables. ● Hash table: ■ Given a table T and a record x, with key (= symbol) and satellite data, we need to support:
Hash table CSC317 We have elements with key and satellite data
Hashing Alexandra Stefan.
CS 332: Algorithms Hash Tables David Luebke /19/2018.
Hashing Alexandra Stefan.
Hashing Alexandra Stefan.
CSE 2331/5331 Topic 8: Hash Tables CSE 2331/5331.
Introduction to Algorithms 6.046J/18.401J
Resolving collisions: Open addressing
Hash Tables – 2 Comp 122, Spring 2004.
Hashing Alexandra Stefan.
Introduction to Algorithms
Data Structures and Algorithms (AT70. 02) Comp. Sc. and Inf. Mgmt
Hashing Sections 10.2 – 10.3 Lecture 26 CS302 Data Structures
CS 5243: Algorithms Hash Tables.
Collision Handling Collisions occur when different elements are mapped to the same cell.
CS 3343: Analysis of Algorithms
Slide Sources: CLRS “Intro. To Algorithms” book website
Hash Tables – 2 1.
Presentation transcript:

Data Structures Dana Shapira Hash Tables 26/06/07

Element Uniqueness Problem Let Determine whether there exist i  j such that x i =x j Sort Algorithm Bucket Sort for (i=0;i<m;i++) T[i]=NULL; for (i=0;i<n;i++){ if (T[x i ]= = NULL) T[x i ]= i else{ output (i, T[x i ]) return; } What happens when n is large or when we are dealing with real numbers?? O(m) O(n) O(m+n)סיבוכיות:

Notations: U universe of keys of size |U|, K an actual set of keys of size n, T a hash table of size O(m) Use a hash-function h:U  {0,…,m-1}, h(x)=i that computes the slot i in array T where element x is to be stored, for all x in U. h(k) is computed in O(|k|) = O(1). x1x1 x2x2 x3x3 x4x4 h(x1)h(x1)h(x2)h(x2)h(x4)h(x4)h(x3)h(x3) U h Set of array indices Hash Tables מספר המפתחותn m גדול הטבלה מניחים שזמן החישוב הוא קבוע טבלאות גיבוב

Example h:U  {0,…, m-1} h(x)=x mod 10 (what is m?) input: 17,62,19,81,53 Collision: x ≠ y but h(x) = h(y). m « |U|. Solutions: 1. Chaining 2. Open addressing m=10 פונקצית הגיבוב היא על אם נרצה להכניס את 82 נקבל בעיית התנגשות: 82!=62 but h(82)=h(62)=2 קטן ממש ביחס לגודל היקוםm

Collision-Resolution by Chaining Insert(T,x): Insert new element x at the head of list T[h(x.key)]. Delete(T,x):Delete element x from list T[h(x.key)]. Search(T,x):Search list T[h(x.key)]. שרשור באמצעות רשימה מקושרת חד כיוונית פעולה של הורדת איבר מרשימה -> חד כיוונית

Simple Uniform Hashing Any given element is equally likely to hash to any slot in the hash table. The slot an element hashes to is independent of where other elements hash. Load factor: α = n/m (elements stored in the hash table / number of slots in the hash table) Analysis of Chaining המטרה היא שהפונקציה תעמוד תחת ההנחה של פונקצית גיבוב אחידה פשוטה – ההסתברות שאלמנט ייפול בכל תא במערך שווה. יש פיזור אחיד של מפתחות. כמו כן נדרוש ששני איברים שונים בטבלה לא יהיו תלויים במיקום אחד של השני. m = Θ(n) → α=O(1) ואז כל הפעולות ייקחו בממוצע זמן קבוע

Analysis of Chaining Theorem: In a hash table with chaining, under the assumption of simple uniform hashing, both successful and unsuccessful searches take expected time Θ(1+α) on the average, where α is the hash table load factor. Proof: Unsuccessful Search: Under the assumption of simple uniform hashing, any key k is equally likely to hash to any slot in the hash table. The expected time to search unsuccessfully for a key k is the expected time to search to the end of list T[h(k)] which has expected length α.  expected time - O(1 + α ) including time for computing h(k). Successful search: The number of elements examined during a successful search is 1 more than the number of elements that appear before k in T[h(k)].  expected time - O(1 + α ) Corollary: If m = O(n), then Insert, Delete, and Search take expected constant time. ניתוח סיבוכיות - שרשור בשני המקרים – חיפוש מוצלח וחיפוש כושל – נקבל סיבוכיות של: Θ(1+α), כאשר ה – 1 משמש לחישוב פונ' הגיבוב עצמה מעבר למקום הבא ברשימהV עוברים על i-1 איברים ומוצאים באיבר ה – i. החלוקה ב – n נעשית כי מדובר בממוצע סיבוכיות: המספר הזה ^ מקיים >4/α וגם <2/ α ומקבלים Θ(1+α)

Example: Input = reals drawn uniformly at random from [0,1) Hash function: h(x) =  mx  Often, the input distribution is unknown. Then we can use heuristics or universal hashing. Designing Good Hash Functions מספרים ממשיים המתפזרים באופן רנדומלי על התחום (0,1] פונ' גיבוב אוניברסלית יוריסטיקות יוריסטיקה: רעיון שלא חייב לעבוד בפועל. רעיון אינטואיטיבי שלא חייב לעבוד במקרה הגרוע, אך בד"כ עובד במקרה הממוצע.

Hash function: h(x) = x mod m m = 2 k  h(x) = the lowest k bits of x Heuristic: m = prime number not too close to a power of 2 The Division Method לא לוקחים את כל הספרות – מתרחק מהנחת הגיבוב האחיד על הטבלה. לכן לא נבחר m כנ"ל, אלא:

Hash function: h(x) =  m (cx mod 1) , for some 0 < c < 1 Optimal choice of c depends on input distribution. Heuristic: Knuth suggests the inverse of the golden ratio as a value that works well: Example: x=123,456, m=10,000 h(x) =  10,000 ·(123,456· … mod 1)  = =  10,000 ·(76, … mod 1)  = =  10,000 · …  =   = 41 The Multiplication Method מה שמופיע אחרי הנקודה בשבר ^ הפונק' הזו יותר טובה, מקודם הפונקציה היתה תלויה בגודל הטבלה וכעת תלויה בקבוע c עפ"י קנוט, c כזה יאפשר גיבוב אחיד על פני הטבלה. גודל טבלהמפתח

Efficient Implementation of the Multiplication Method w bits p bits * Fractional part Integer part after multiplying by m = 2 p Let w be the size of a machine word Assume that key x fits into a machine word Assume that m = 2 p Restrict ourselves to values of c of the form c = s / 2 w Then cx = sx / 2 w sx is a number that fits into two machine words h(x) = p most significant bits of the lower word h(x) =  m (cx mod 1)  ע"י בחירה מתאימה של קבוע c, ניתן לבצע זאת עם פעולות של ביטים. בסופו של דבר, נסתכל על p הביטים העליונים במילה התחתונה. ניקח: Sx נכנס לכל היותר ב-2 מילות מכונה

x = , p = 14, m = 2 14 = 16384, w = 32, Then sx = (76300 ⋅ 2 32 ) The 14 most significant bits of are 67; that is, h(x) = 67 x = s = sx = h(x) = = 67 Example h(x) =  m (cx mod 1)  32 bitמפתח הייצוג של : הרצף הבינארי של : (די דילגנו, כי לא למדנו ייצוג בינארי של מספרים)

Open Addressing h(x)h(x) All elements are stored directly in the hash table. Load factor α cannot exceed 1. If slot T[h(x)] is already occupied for a key x, we probe alternative locations until we find an empty slot. Searching probes slots starting at T[h(x)] until x is found or we are sure that x is not in T. Instead of computing h(x), we compute h(x, i) i -the probe number. זהו הנידסיון להכניס איבר. → בפעם הראשונה i=0 המחיקה לא מתבצעת באופן ישיר. צריך דגל שיסמן – תפוס לצרכי חיפוש אך פנו לצרכי הכנסה. אחרת אם למשל הכנסנו איבר ראשון ב – I ואיבר שני ב – II, ואז מחקנו את האיבר מ – I, לא יהיה לנו איך להגיע לאיבר ב – II. III

Linear Probing Hash function: h(k, i) = (h'(k) + i) mod m, where h' is an original hash function. Benefits: Easy to implement Problem: Primary Clustering - Long runs of occupied slots build up as table becomes fuller. דוגמא: h’(x) = k mod7 h’(9) h(16,0) = h’(16) = 2 h(16,1) = (h’(16)+1) mod 7 = 3 (האחד נוסף בגלל הבדיקה) חיסרון: כל מספר חדש יצטרך לדלג – פוגעים בהנחת ההתפלגות האחידה כי נוצרים "בלוקים" בטבלה. מקבלים התאגדות ראשונית ← יתרון: קל להכניס לתאים. פתרון אפשרי (בעמוד הבא) – לקחת קבועים ולעלות בריבוע כדי שלא ייכנס למקום הפנוי הבא

Hash function: h(k, i) = (h'(k) + c 1 i + c 2 i 2 ) mod m, where h' is an original hash function. Benefits: No more primary clustering Problem: Secondary Clustering - Two elements x and y with h'(x) = h'(y) have same probe sequence. Quadratic Probing נוצרת התאגדות שניונית

Hash function: h(k, i) = (h 1 (k) + ih 2 (k)) mod m, where h 1 and h 2 are two original hash functions. h 2 (k) has to be prime w.r.t. m; that is, gcd(h 2 (k), m) = 1. Two methods: Choose m to be a power of 2 and guarantee that h 2 (k) is always odd. Choose m to be a prime number and guarantee that h 2 (k) < m. Benefits: No more clustering Drawback: More complicated than linear and quadratic probing Double Hashing פתרון נוסף – שתי פונקציות גיבוב חסרון – צורך בשתי פונ' hash h 2 (k)!=0 אחרת לא נגיע לכל המקומות בטבלה i = מס' הדגימה

Analysis of Open Addressing Uniform hashing: The probe sequence h(k, 0), …, h(k, m – 1) is equally likely to be any permutation of 0, …, m – 1. Theorem: In an open-address hash table with load factor α < 1, the expected number of probes in an unsuccessful search is at most 1 / (1 – α ), assuming uniform hashing. Proof: Let X be the number of probes in an unsuccessful search. A i = “there is an i-th probe, and it accesses a non-empty slot” הנחה חדשה במקום הנחת הגיבוב הפשוט – הסתברות קבל כל אחד מהמספרים תהיה אחידה (הוכחה בהסתברות – עברנו על זה באופן כללי)

Analysis of Open Addressing – Cont. ההסתברות שתא תפוס בבדיקה הראשונה ההסתברות בבדיקה השניה, בהנחה שגילינו תא תפוס ב – A1 ובאופן כללי – התא ה – j תפוס בהנחה ש – 1…..j-1 תפוסים

Corollary: The expected number of probes performed during an insertion into an open-address hash table with uniform hashing is 1 / (1 – α). Analysis of Open Addressing – Cont.

A successful search for an element x follows the same probe sequence as the insertion of element x. Consider the (i + 1)-st element x that was inserted. The expected number of probes performed when inserting x is at most Averaging over all n elements, the expected number of probes in a successful search is Theorem: Given an open-address hash table with load factor α < 1, the expected number of probes in a successful search is (1/ α ) ln (1 / (1 – α )), assuming uniform hashing and assuming that each key in the table is equally likely to be searched for. Analysis of Open Addressing – Cont.

A family  of hash functions is universal if for each pair k, l of keys, there are at most |  | / m functions in  such that h(k) = h(l). This means: For any two keys k and l and any function h chosen uniformly at random, the probability that h(k) = h(l) is at most 1/m. P= (|  | / m )/ |  | =1/m This is the same as if we chose h(k) and h(l) uniformly at random from [0, m – 1]. Universal Hashing גיבוב אוניברסלי. משפחות של פונקציות גיבוב – בוחרים באופן רנדומלי פונ' גיבוב ומבצעים את כל הפעולות איתה. לכל זוג מפתחות, ההסתברות להתנגשות היא 1/m לא עברנו על הוכחות הסיבוכיות בהמשך

Analysis of Universal Hashing Theorem: For a hash function h chosen uniformly at random from a universal family , the expected length of the list T[h(x)] is α if x is not in the hash table and 1 + α if x is in the hash table. Proof: Indicator variables: Y x = the number of keys ≠ x that hash to the same slot as x

If x is not in T, then |{y  T : x ≠ y}| = n. Hence, E[Y x ] = n / m = α. If x is in T, then |{y  T : x ≠ y} = n – 1. Hence, E[Y x ] = (n – 1) / m < α. The length of list T[h(x)] is one more, that is, 1 + α. Analysis of Universal Hashing Cont.

Universal Family of Hash Functions Choose a prime p so that m = p. Let such For each define the hash function as follows:  =  |  | = Example: m=p=253 a=[248,223,101] x=1025=[0,2,1] . בוחרים באופן רנדומלי מספר, המורכב מ – r+1 איברים בתחום 0,……,m-1 לפיזור על הטבלה ↑ זה נכון, כי לוקחים כל אחד מה – a i להיות 0,….,m-1 (סה"כ m), ויש r+1 a i. תחום המפתחות מגרילים מספר a המורכב מ-3 חלקים, כל חלק לכל היותר 255 פה יש טעות, זה לא באמת 1025 בבינארית קצת בינארית: = = = 255 אם המפתח הוא 1025: | | (אני לא בטוחה לגבי זה)

Universal Family of Hash Functions Theorem: The class  is universal. Proof: Let such that x ≠ y, w.l.o.g For all a 1,…,a r there exists a single a 0 such that For all there exists a single w such that z·w=1(mod m) for m r values The number of hash functions h in , for which h(k 1 ) = h(k 2 ) is at most m r/ m r+1 =1/m למדנו ש – Zp הוא שדה, ולכן לכל מס' שונה מ-0 יש הופכי

Universal Family of Hash Functions Choose a prime p so that m < p. For any 1 ≤ a < p and 0 ≤ b < p, we define a function h a,b (x) = ((ax + b) mod p) mod m. Let H p,m be the family H p,m = {h a,b : 1 ≤ a < p and 0 ≤ b < p}. Theorem: The class H p,m is universal. h(k,i) = (h1(k) + ih2(k))mod11 h1(k) = k mod11 h2(k) = k md (האחד כדי שפונ' הגיבוב השניה תהיה שונה מאפס, אחרת i לא יקודם) דוגמא: insert(133) תפוס – משתמשים בפונ' השנייה 39 תפוס – משתמשים בפונ' השנייה h(37,0) = 4 h(67,0) = 1 תפוס! h(67,1) = 4 תפוס! h(67,2) = 1+2x3 = 7 deleted(133) search(189) h(89,0) = 1 h(89,1) מחקנו את 133, ולכן תפוס לצרכי חיפוש

Hash tables are the most efficient dictionaries if only operations Insert, Delete, and Search have to be supported. If uniform hashing is used, the expected time of each of these operations is constant. Universal hashing is somewhat complicated, but performs well even for adversarial input distributions. If the input distribution is known, heuristics perform well and are much simpler than universal hashing. For collision-resolution, chaining is the simplest method, but it requires more space than open addressing. Open addressing is either more complicated or suffers from clustering effects. Summary