Docsity

Data Structures: Binary Search Trees and Hash Tables, Study notes of Algorithms and Programming

Partial preview of the text

Download Data Structures: Binary Search Trees and Hash Tables and more Study notes Algorithms and Programming in PDF only on Docsity!

CPSC 311 Lecture Notes

Data Structures

(Chapters 10-12)

Acknowledgement: These notes are compiled by Nancy Amato at Texas A&M University. Parts of these course notes are based on notes from courses given by Jennifer Welch at Texas A&M University.

Data Structures for (Dynamic) Sets

Algorithms operate on data, which can be thought of as forming a set S. Unlike mathematical sets, the (data) sets manipulated by algorithms are dynamic – they can grow, shrink, or otherwise change over time.

Data Structures are structured ways to represent finite dynamic sets. Dif- ferent data structures support different kinds of data manipulations, e.g.,

  • dictionary: insert, delete, membership test
  • priority queue: insert, extract-min

Operations on Dynamic Sets:

  • Insert(S, x) adds element pointed to by x to S
  • Delete(S, x) removes element pointed to by x from S.
  • Search(S, k) returns pointer to element x with key[x] = k (or nil)
  • Minimum(S) returns element with the smallest key
  • Maximum(S) returns element with the largest key
  • Successor(S, x) returns element with the next key larger than key[x]
  • Predecessor(S, x) returns element with the next key smaller than key[x]

Running Time: usually measure time of an operation in terms of the number of elements (currently) in the set.

Binary Search Trees

Binary Search Trees should also be review from CPSC 211 (Chapt 12). Recall, every tree node (internal or leaf) contains a key.

Binary Search Tree Property: For every node x in tree

  • key[y] ≤ key[x] for every y in lef t(x) (left subtree)
  • key[y] ≥ key[x] for every y in right(x) (right subtree)

(Note there is no condition on the height h of tree)

Operations on BSTs (supports all dynamic data set ops)

  • Insert(S, x), Delete(S, x)
  • Search(S, k), Minimum(S), Maximum(S)
  • Successor(S, x), Predecessor(S, x)

Running Time: All operations take O(h) time

Traversing (visiting) BSTs

  • in-order: visit lef t(x), visit x, visit right(x)
  • pre-order: visit x, visit lef t(x), visit right(x)
  • post-order: visit lef t(x), visit right(x), visit x

Binary Search Tree Operations

Tree-Search(x, k) if (x = N IL) or (k = key[x]) return x if (k < key[x]) then return Tree-Search(lef t[x], k) else return Tree-Search(right[x], k)

Tree-Successor(x, k) if right[x] 6 = N IL then return Tree-Minimum(right[x]) temp := parent[x] while (temp 6 = N IL and x = right[temp]) x := temp temp := parent[temp] return temp

Note:

  • if x has a rightchild, then successor(x) is the smallest node in the subtree rooted right[x]
  • if x has no rightchild, then successor(x) is the lowest ancestor of x whose leftchild is also an ancestor of x (or x itself)
  • predecessor is symmetrical

Hash Tables

Dictionary operations

  • search(k)
  • insert(x)
  • delete(x)

Definition: U = Universe from which keys are drawn (often N , natural numbers) K ⊆ U set of keys seen

Goals:

  • fast implementation of all operations — O(1) time
  • space efficient data structure — O(n) space if n elements in dictionary

Approach 1: Linked Lists

Linked List Implementation

  • insert(x): add x at head of list
  • search(k): start at head and scan list
  • delete(x): start at head, scan list, and then delete

Running Times: (assume n elements in list)

  • insert(x): O(1) time
  • search(k):
    • worst-case, element at end of list: n operations
    • average-case, element at middle of list: n/2 operations
    • best-case, element at head of list: 1 operation
  • delete(x): same as searching...

This is pretty bad.... we’d like O(1) time on average for all operations....

Space Usage: (assume n elements in list)

  • O(n) space – very space efficient...

This is great!

Approach 3: Hashing

Hashing

  • hash table (an array) H[0, m] where m << |U |
    • amount of storage closer to what is really needed
  • hash function h maps keys to indices in H
    • h : U → { 0 , 1 ,... , m}

Problem: there will be some collisions, that is, h will map some keys to the same position in H (e.g., h(k 1 ) = h(k 2 ) for k 1 6 = k 2 )

Different Methods of Resolving Collisions

  1. chaining: put all elements that hash to the same location in a linked list
  2. open addressing: successively examine of probe H until find an empty slot (or the element you are looking for). There are various types of probe sequences: - linear probing – probe successive slots - quadratic probing – probes offset by quadratically increasing values - double hashing – a 2nd hash function determines probe sequence

Later we’ll consider how to pick good hash functions h. Assume for now our hash function h satisfies:

Simple Uniform Hashing Assumption: Any key is equally likely to hash to any location (index,slot) in hash table H.

Collision Resolution by Chaining

Chaining: put all keys that hash to the same location in a linked list

0 1 i m-

y

x h(x) = h(y) = i

H:

  • insert(x): compute h(x) and insert x at head of linked list in H[h(x)]
    • O(1) time always
  • search(x): compute h(x) and search linked list in H[h(x)]
    • O(n) time in worst-case
  • delete(x): compute h(x) and search linked list H[h(x)] for x
    • O(n) time in worst-case
    • (can be O(1) time if know where x is and list is doubly linked)

Note: even though worst-case behavior is Θ(n), the idea of hashing is to achieve good average-case behavior. Usually, we can get average-case time of operations down to Θ(1).

Average-Case Analysis for search(x) with Chaining

Case 2: average search(x) time when x is in table

  • = Θ(1) to compute h(x)
    • expected # elements examined in H[h(x)]’s list until find x

Note: this is easier to analyze if we assume elements are added at end of lists (can prove average successful search time is the same regardless).

  • = Θ(1) to compute h(x)
    • expected length of H[h(x)] when x was inserted +

Fact: if x is the ith element added to H, then the expected length of H[h(x)]’s list before adding x is i− m^1

∑n i=

Pr(x is ith elt added) · (length of H[h(x)] + 1)

= Θ(1) + ∑n i=

n

  i^ −^1 m

 

∑n i=

i − 1 nm

∑n i=

n = Θ(1) +

nm

∑^ n i=

(i − 1) +

n

∑^ n i=

nm

(n − 1)n 2

n

· n

= Θ(1) + n 2 m

2 m

· α −

2 m

  • 1 = Θ(1 + α)

So... average search(x) time is Θ(1 + α)

  • Θ(1) if α = Θ(1) (choose m ≥ n and m = Θ(n))

Choosing Hash Functions

Ideally, hash function satisfies:

Simple Uniform Hashing Assumption: Any key is equally likely to hash to any location (index,slot) in hash table H.

unfortunately, we cannot usually achieve this... so we use heuristics

For indexing in H is is convenient for keys to be natural numbers (0, 1 , 2 ,.. .)

  • this is not usually a problem
    • character strings =⇒ interpret characters as numbers
    • real numbers =⇒ floor, ceiling (scale)

Division Method for creating hash functions

  • h(k) = k mod m (reminder when divide k by m)
  • important to pick ‘good’ value for m, e.g., a prime number close to actual # of slots you want

Multiplicatoin Method for creating hash functions

  • h(k) = bm(kA mod 1)c
  • A is some constant 0 < A < 1
  • kA mod 1 is ‘fractional part’ of kA (i.e., kA − bkAc)
  • the value selected for m is not as critical as for the division method
    • can get efficiency by choosing m = 2p^ for some constant p (p. 229)

Collision Resolution by Open Addressing

Ideally, we have

Uniform Hashing Assumption: each key is equally likely to have any of the m! permutations (of indices in H) as its probe sequence

Note: this is different from simple uniform hashing:

  • simple uniform: each key hashes to each of m slots with prob (^) m^1
  • uniform: each key hashes to each of m! probe sequences with prob (^) m^1!

Again, this is hard to achieve, so we usually settle for heurestics...

Linear Probing (Open Addressing)

Linear Probing: the ith probe h(k, i) is

h(k, i) = (h′(k) + i) mod m

  • h′(k) is ordinary hash function, tells where to start the search
  • search sequentially through table (with wrap around) from starting point

How many distinct probe sequences are there? m

  • each starting point gives a probe sequence
  • there are m starting points
  • =⇒ not uniform (need m! probe sequences)

Pluses and Minuses

  • plus: easy to implement
  • minus: leads to clustering (long run of occupied slots in H)
    • yields bad performance if hit cluster

Double Hashing (Open Addressing)

Double Hashing: the ith probe h(k, i) is

h(k, i) = (h 1 (k) + h 2 (k) · i) mod m

  • h 1 (k) is ordinary hash function, tells where to start the search
  • h 2 (k) is ordinary hash function which gives offset for subsequent probes

Important: to make sure probe sequence hits all slots in H we must have h 2 (k) be relatively prime to m

Example 1:

  • m is prime
  • h 1 (k) = k mod m
  • h 2 (k) = 1 + (k mod (m − 1))

Example 2:

  • m is power of 2
  • h 1 (k) = k mod m
  • h 2 (k) is always odd

How many distinct probe sequences are there? m^2

  • there are m starting points
  • starting point and offset can vary independently
  • better, but still not uniform...

Analyzing Open Addressing

We now analyze the expected number of probes for open addressing

  • assume uniform hashing (all m! probe sequences equally likely)
  • α = (^) mn (load factor) so we need α ≤ 1 (table cannot be overfull)

Theorem: If α < 1 , then the expected number of probes in an unsuccessful search is ≤ (^1) −^1 α

Proof: In an unsuccessful search when α < 1 (table not full), some number of probes access occupied slots and the last probe accesses an empty slot.

E(#probes) = 1 + E(#probes that access occupied slots)

= 1 + ∑∞ i=

i · Pr[exactly i probes access occupied slots]

= 1 + ∑∞ i=

Pr[exactly i probes access occupied slots] /identity/

≤ 1 + ∑∞ i=

αi/proof below/

=

1 − α 2