Hash functions KLA

  • I'm going hash all of you into 10 buckets (0-9) by your birthday
  • The hash functions:
    • By the decade of your birth year
      • hash(birthday) = (year/10) % 10
    • By the last digit of your birth year
      • hash(birthday) = year % 10
    • By the last digit of your birth month
      • hash(birthday) = month % 10
    • By the last digit of your birth day
      • hash(birthday) = day % 10

Example: On Board

  • Key space: integers
     
  • Table size: 10
     
  • hash(k) = k mod 10
    • Technically, hash(k) = k,
      which is then mod'ed by
      the table size of 10
       
  • Insert: 7, 18, 41, 34
     
  • How do we find them?

Another Example

  • Key space: integers
     
  • Table size: 6
     
  • hash(k) = k mod 6
     
  • Insert: 7, 18, 41, 34, 12
     
  • How do we find them?

Separate Chaining

  • All keys that map to the same hash value are kept in a "bucket"
    • This "bucket" is another data structure, typically a linked list

     
  • hash(k) = k mod 10
     
  • Insert: 10, 22, 107, 12, 42

Linear Probing

  • Check spots in this order:
    • hash(k), hash(k)+1, hash(k)+2, etc.
     
  • hash(k) = 3k+7
    • Which is then mod'ed by the table size (10)
    • Result: hash(k) = (3k+7) mod 10
     
  • Insert: 4, 27, 37, 14, 21
    • hash(k) values: 19, 88, 118, 49, 70, respectively

Quadratic Probing

  • Check spots in this order:
    • hash(k)
    • hash(k)+12 = hash(k)+1
    • hash(k)+22 = hash(k)+4
     
  • hash(k) = 3k+7
    • Insert: 4, 27, 14, 37, 22, 34
      • hash(k) values: 19, 88, 49, 118, 73, 109, respectively

Double Hashing

  • Check spots in this order:
    • hash(k)
    • hash(k) + 1 * hash2(k)
    • hash(k) + 2 * hash2(k)
     
  • hash(k) = k
    • Result: hash(k) = k mod 10
  • hash2(k) = 7 - (k mod 7)
     
  • Insert: 89, 18, 58, 49, 69, 60

Double Hashing Thrashing

  • hash(k) = k mod 10 
    • Same as the previous slide
    • Result: hash(k) = k mod 10
     
  • hash2(k) = (k mod 5) +1
     
  • Insert: 10, 12, 14, 16, 18, 36