Docsity

Hashing - Data Structures - Lecture Slides, Slides of Data Structures and Algorithms

Partial preview of the text

Download Hashing - Data Structures - Lecture Slides and more Slides Data Structures and Algorithms in PDF only on Docsity!

Hashing

Sorting Objects

  • When sorting an array of objects we aremanipulating references to the object, and not

the objects themselves

4

The Search Problem

  • Unsorted list – O(N)
  • Sorted list – O(logN) using arrays (i.e., binary search)
  • Binary Search tree^ –^ O(N) using linked lists
    • – O(logN) (i.e., balanced tree)O(N) (i.e., unbalanced tree)
  • Can we do better than this? – Direct Addressing
    • Hashing Docsity.com

5

Direct Addressing

  • Assumptions:
    • Key values are distinct
    • Each key is drawn from a universe U = {0, 1,... , n - 1}
  • Idea:
    • Store the items in an array, indexed by keys

7

Direct Addressing (cont’d)

Example 1: Suppose that the are integers from 1 to 100 and that there are about 100 records. Create an array A of 100 items and stored the record whose key is equal to i in in A[i].

|K| = |U| |K|: # elements in K |U|: # elements in U

8

Direct Addressing (cont’d)

Example 2: Suppose that the keys are 9-digit social security numbers (SSN) Although we could use the same idea, it would be very inefficient (i.e., use an array of 1 billion size to store 100 records)

|K| << |U|

Hashing

  • is a means used to order and access elementsin a list quickly by using a function of the key

value to identify its location in the list. • the goal is O(1) time

  • The function of the key value is called a hashfunction.

11

Hashing

Idea:

  • Use a function h to compute the slot for each key
  • Store the element in slot h(k)
  • A hash function h transforms a key into an

index in a hash table T[0…m-1]:

h : U → {0, 1,... , m - 1}

  • We say that k hashes to slot h(k)

13

Hashing (cont’d)

Example 2: numbers (SSN) Suppose that the keys are 9-digit social security

Advantages of Hashing

  • Reduce the range of array indices handled:

m instead of |U|

where m is the hash table size: T[0, …, m-1]

  • Storage is reduced.
  • O(1) search time (i.e., under assumptions).

16

The Division Method

  • Idea: – Map a key k into one of the m slots by taking

the remainder of h(k) = k mod m k divided by m

  • Advantage – fast, requires only one operation:
  • Disadvantage – Certain values of: m are bad (i.e., collisions), e.g.,
    • • power of 2non-prime numbers

17

Example

  • Ifsignificant m = 2p, then p bits of h(k) kis just the least
    • (^) ⇒p = 1 h(k) = ⇒ m = 2, least significant 1 bit of k
    • ⇒ p = 2 h(k) = ⇒ m = 4 , least significant 2 bits of k

 Choose m to be a prime, not close to a

^ power of 2 Column 2:

 Column 3:

{0, 1} {0, 1, 2, 3}

k mod 100^ k mod 97

m 97 m 100

19

Example – Multiplication Method

Suppose k=6, A=0.3, m= (1) k x A = 1. (2) fractional part: (3) m x 0.8 = 32 x 0.8 = 25. (4)

 25.6^  =^25 h(6)=