Presentation is loading. Please wait.

Presentation is loading. Please wait.

Elementary Data Structures Stacks, Queues, Lists, Vectors, Sequences, Trees, Priority Queues, Heaps, Dictionaries & Hash Tables.

Similar presentations


Presentation on theme: "Elementary Data Structures Stacks, Queues, Lists, Vectors, Sequences, Trees, Priority Queues, Heaps, Dictionaries & Hash Tables."— Presentation transcript:

1 Elementary Data Structures Stacks, Queues, Lists, Vectors, Sequences, Trees, Priority Queues, Heaps, Dictionaries & Hash Tables

2 Elementary Data Structures2 The Stack ADT (§2.1.1) The Stack ADT stores arbitrary objects Insertions and deletions follow the last-in first-out scheme Think of a spring-loaded plate dispenser Main stack operations: push(object): inserts an element object pop(): removes and returns the last inserted element Auxiliary stack operations: object top(): returns the last inserted element without removing it integer size(): returns the number of elements stored boolean isEmpty(): indicates whether no elements are stored

3 Elementary Data Structures3 Applications of Stacks Direct applications Page-visited history in a Web browser Undo sequence in a text editor Chain of method calls in the Java Virtual Machine or C++ runtime environment Indirect applications Auxiliary data structure for algorithms Component of other data structures

4 Elementary Data Structures4 The Queue ADT (§2.1.2) The Queue ADT stores arbitrary objects Insertions and deletions follow the first-in first-out scheme Insertions are at the rear of the queue and removals are at the front of the queue Main queue operations: enqueue(object): inserts an element at the end of the queue object dequeue(): removes and returns the element at the front of the queue Auxiliary queue operations: object front(): returns the element at the front without removing it integer size(): returns the number of elements stored boolean isEmpty(): indicates whether no elements are stored Exceptions Attempting the execution of dequeue or front on an empty queue throws an EmptyQueueException

5 Elementary Data Structures5 Applications of Queues Direct applications Waiting lines Access to shared resources (e.g., printer) Multiprogramming Indirect applications Auxiliary data structure for algorithms Component of other data structures

6 Elementary Data Structures6 Position ADT The Position ADT models the notion of place within a data structure where a single object is stored It gives a unified view of diverse ways of storing data, such as a cell of an array a node of a linked list Just one method: object element(): returns the element stored at the position

7 Elementary Data Structures7 List ADT (§2.2.2) The List ADT models a sequence of positions storing arbitrary objects It allows for insertion and removal in the “middle” Query methods: isFirst(p), isLast(p) Accessor methods: first(), last() before(p), after(p) Update methods: replaceElement(p, o), swapElements(p, q) insertBefore(p, o), insertAfter(p, o), insertFirst(o), insertLast(o) remove(p)

8 Elementary Data Structures8 Singly Linked List A singly linked list is a concrete data structure consisting of a sequence of nodes Each node stores element link to the next node next elem node ABCD 

9 Elementary Data Structures9 Doubly Linked List A doubly linked list provides a natural implementation of the List ADT Nodes implement Position and store: element link to the previous node link to the next node Special trailer and header nodes prevnext elem trailer header nodes/positions elements node

10 Elementary Data Structures10 The Vector ADT The Vector ADT extends the notion of array by storing a sequence of arbitrary objects An element can be accessed, inserted or removed by specifying its rank (number of elements preceding it) An exception is thrown if an incorrect rank is specified (e.g., a negative rank) Main vector operations: object elemAtRank(integer r): returns the element at rank r without removing it object replaceAtRank(integer r, object o): replace the element at rank with o and return the old element insertAtRank(integer r, object o): insert a new element o to have rank r object removeAtRank(integer r): removes and returns the element at rank r Additional operations size() and isEmpty()

11 Elementary Data Structures11 Applications of Vectors Direct applications Sorted collection of objects (elementary database) Indirect applications Auxiliary data structure for algorithms Component of other data structures

12 Elementary Data Structures12 Sequence ADT The Sequence ADT is the union of the Vector and List ADTs Elements accessed by Rank, or Position Generic methods: size(), isEmpty() Vector-based methods: elemAtRank(r), replaceAtRank(r, o), insertAtRank(r, o), removeAtRank(r) List-based methods: first(), last(), before(p), after(p), replaceElement(p, o), swapElements(p, q), insertBefore(p, o), insertAfter(p, o), insertFirst(o), insertLast(o), remove(p) Bridge methods: atRank(r), rankOf(p)

13 Elementary Data Structures13 Applications of Sequences The Sequence ADT is a basic, general- purpose, data structure for storing an ordered collection of elements Direct applications: Generic replacement for stack, queue, vector, or list small database (e.g., address book) Indirect applications: Building block of more complex data structures

14 Elementary Data Structures14 Trees (§2.3) In computer science, a tree is an abstract model of a hierarchical structure A tree consists of nodes with a parent-child relation Applications: Organization charts File systems Programming environments Computers”R”Us SalesR&DManufacturing LaptopsDesktops US International EuropeAsiaCanada

15 Elementary Data Structures15 subtree Tree Terminology Root: node without parent (A) Internal node: node with at least one child (A, B, C, F) External node (a.k.a. leaf ): node without children (E, I, J, K, G, H, D) Ancestors of a node: parent, grandparent, grand-grandparent, etc. Depth of a node: number of ancestors Height of a tree: maximum depth of any node (3) Descendant of a node: child, grandchild, grand-grandchild, etc. A B DC GH E F IJ K Subtree: tree consisting of a node and its descendants

16 Elementary Data Structures16 Tree ADT (§2.3.1) We use positions to abstract nodes Generic methods: integer size() boolean isEmpty() objectIterator elements() positionIterator positions() Accessor methods: position root() position parent(p) positionIterator children(p) Query methods: boolean isInternal(p) boolean isExternal(p) boolean isRoot(p) Update methods: swapElements(p, q) object replaceElement(p, o) Additional update methods may be defined by data structures implementing the Tree ADT

17 Elementary Data Structures17 Preorder Traversal (§2.3.2) A traversal visits the nodes of a tree in a systematic manner In a preorder traversal, a node is visited before its descendants Application: print a structured document Make Money Fast! 1. MotivationsReferences2. Methods 2.1 Stock Fraud 2.2 Ponzi Scheme 1.1 Greed1.2 Avidity 2.3 Bank Robbery 1 2 3 5 4 678 9 Algorithm preOrder(v) visit(v) for each child w of v preorder (w)

18 Elementary Data Structures18 Postorder Traversal (§2.3.2) In a postorder traversal, a node is visited after its descendants Application: compute space used by files in a directory and its subdirectories Algorithm postOrder(v) for each child w of v postOrder (w) visit(v) cs16/ homeworks/ todo.txt 1K programs/ DDR.java 10K Stocks.java 25K h1c.doc 3K h1nc.doc 2K Robot.java 20K 9 3 1 7 2 456 8

19 Elementary Data Structures19 Inorder Traversal In an inorder traversal a node is visited after its left subtree and before its right subtree Application: draw a binary tree x(v) = inorder rank of v y(v) = depth of v Algorithm inOrder(v) if isInternal (v) inOrder (leftChild (v)) visit(v) if isInternal (v) inOrder (rightChild (v)) 3 1 2 5 6 79 8 4

20 Elementary Data Structures20 Binary Trees (§2.3.3) A binary tree is a tree with the following properties: Each internal node has two children The children of a node are an ordered pair We call the children of an internal node left child and right child Alternative recursive definition: a binary tree is either a tree consisting of a single node, or a tree whose root has an ordered pair of children, each of which is a binary tree Applications: arithmetic expressions decision processes searching A B C FG D E H I

21 Elementary Data Structures21 Properties of Binary Trees Notation n number of nodes e number of external nodes i number of internal nodes h height Properties: e  i  1 n  2e  1 h  i h  (n  1)  2 e  2 h h  log 2 e h  log 2 (n  1)  1

22 Elementary Data Structures22 Array-Based Representation of Binary Trees nodes are stored in an array … let rank(node) be defined as follows: rank(root) = 1 if node is the left child of parent(node), rank(node) = 2*rank(parent(node)) if node is the right child of parent(node), rank(node) = 2*rank(parent(node))+1 1 23 6 7 45 1011 A HG FE D C B J

23 Elementary Data Structures23 Priority Queue ADT A priority queue stores a collection of items An item is a pair (key, element) Main methods of the Priority Queue ADT insertItem(k, o) inserts an item with key k and element o removeMin() removes the item with smallest key and returns its element Additional methods minKey(k, o) returns, but does not remove, the smallest key of an item minElement() returns, but does not remove, the element of an item with smallest key size(), isEmpty() Applications: Standby flyers Auctions Stock market

24 Elementary Data Structures24 What is a heap (§2.4.3) A heap is a binary tree storing keys at its internal nodes and satisfying the following properties: Heap-Order: for every internal node v other than the root, key(v)  key(parent(v)) Complete Binary Tree: let h be the height of the heap  for i  0, …, h  1, there are 2 i nodes of depth i  at depth h  1, the internal nodes are to the left of the external nodes 2 65 79 The last node of a heap is the rightmost internal node of depth h  1 last node

25 Elementary Data Structures25 Height of a Heap (§2.4.3) Theorem: A heap storing n keys has height O(log n) Proof: (we apply the complete binary tree property) Let h be the height of a heap storing n keys Since there are 2 i keys at depth i  0, …, h  2 and at least one key at depth h  1, we have n  1  2  4  …  2 h  2  1 Thus, n  2 h  1, i.e., h  log n  1 1 2 2h22h2 1 keys 0 1 h2h2 h1h1 depth

26 Elementary Data Structures26 Dictionary ADT The dictionary ADT models a searchable collection of key- element items The main operations of a dictionary are searching, inserting, and deleting items Multiple items with the same key are allowed Applications: address book credit card authorization mapping host names (e.g., cs16.net) to internet addresses (e.g., 128.148.34.101) Dictionary ADT methods: findElement(k): if the dictionary has an item with key k, returns its element, else, returns the special element NO_SUCH_KEY insertItem(k, o): inserts item (k, o) into the dictionary removeElement(k): if the dictionary has an item with key k, removes it from the dictionary and returns its element, else returns the special element NO_SUCH_KEY size(), isEmpty() keys(), Elements()

27 Elementary Data Structures27 Binary Search Binary search performs operation findElement(k) on a dictionary implemented by means of an array-based sequence, sorted by key similar to the high-low game at each step, the number of candidate items is halved terminates after a logarithmic number of steps Example: findElement(7) 13457 8 91114161819 1 3 457891114161819 134 5 7891114161819 1345 7 891114161819 0 0 0 0 m l h m l h m l h l  m  h

28 Elementary Data Structures28 Lookup Table A lookup table is a dictionary implemented by means of a sorted sequence We store the items of the dictionary in an array-based sequence, sorted by key We use an external comparator for the keys Performance: findElement takes O(log n) time, using binary search insertItem takes O(n) time since in the worst case we have to shift n  2 items to make room for the new item removeElement take O(n) time since in the worst case we have to shift n  2 items to compact the items after the removal The lookup table is effective only for dictionaries of small size or for dictionaries on which searches are the most common operations, while insertions and removals are rarely performed (e.g., credit card authorizations)

29 Elementary Data Structures29 Binary Search Tree A binary search tree is a binary tree storing keys (or key-element pairs) at its internal nodes and satisfying the following property: Let u, v, and w be three nodes such that u is in the left subtree of v and w is in the right subtree of v. We have key(u)  key(v)  key(w) External nodes do not store items An inorder traversal of a binary search trees visits the keys in increasing order 6 92 418

30 Elementary Data Structures30 Hash Functions and Hash Tables (§2.5.2) A hash function h maps keys of a given type to integers in a fixed interval [0, N  1] Example: h(x)  x mod N is a hash function for integer keys The integer h(x) is called the hash value of key x A hash table for a given key type consists of Hash function h Array (called table) of size N When implementing a dictionary with a hash table, the goal is to store item (k, o) at index i  h(k)

31 Elementary Data Structures31 Example We design a hash table for a dictionary storing items (SSN, Name), where SSN (social security number) is a nine-digit positive integer Our hash table uses an array of size N  10,000 and the hash function h(x)  last four digits of x     0 1 2 3 4 9997 9998 9999 … 451-229-0004 981-101-0002 200-751-9998 025-612-0001

32 Elementary Data Structures32 Hash Functions (§ 2.5.3) A hash function is usually specified as the composition of two functions: Hash code map: h 1 : keys  integers Compression map: h 2 : integers  [0, N  1] The hash code map is applied first, and the compression map is applied next on the result, i.e., h(x) = h 2 (h 1 (x)) The goal of the hash function is to “disperse” the keys in an apparently random way

33 Elementary Data Structures33 Hash Code Maps (§2.5.3) Memory address: We reinterpret the memory address of the key object as an integer (default hash code of all Java objects) Good in general, except for numeric and string keys Integer cast: We reinterpret the bits of the key as an integer Suitable for keys of length less than or equal to the number of bits of the integer type (e.g., byte, short, int and float in Java) Component sum: We partition the bits of the key into components of fixed length (e.g., 16 or 32 bits) and we sum the components (ignoring overflows) Suitable for numeric keys of fixed length greater than or equal to the number of bits of the integer type (e.g., long and double in Java)

34 Elementary Data Structures34 Hash Code Maps (cont.) Polynomial accumulation: We partition the bits of the key into a sequence of components of fixed length (e.g., 8, 16 or 32 bits) a 0 a 1 … a n  1 We evaluate the polynomial p(z)  a 0  a 1 z  a 2 z 2  … …  a n  1 z n  1 at a fixed value z, ignoring overflows Especially suitable for strings (e.g., the choice z  33 gives at most 6 collisions on a set of 50,000 English words) Polynomial p(z) can be evaluated in O(n) time using Horner’s rule: The following polynomials are successively computed, each from the previous one in O(1) time p 0 (z)  a n  1 p i (z)  a n  i  1  zp i  1 (z) (i  1, 2, …, n  1) We have p(z)  p n  1 (z)

35 Elementary Data Structures35 Compression Maps (§2.5.4) Division: h 2 (y)  y mod N The size N of the hash table is usually chosen to be a prime The reason has to do with number theory and is beyond the scope of this course Multiply, Add and Divide (MAD): h 2 (y)  (ay  b) mod N a and b are nonnegative integers such that a mod N  0 Otherwise, every integer would map to the same value b

36 Elementary Data Structures36 Collision Handling (§ 2.5.5) Collisions occur when different elements are mapped to the same cell Chaining: let each cell in the table point to a linked list of elements that map there Chaining is simple, but requires additional memory outside the table    0 1 2 3 4 451-229-0004981-101-0004 025-612-0001

37 Elementary Data Structures37 Linear Probing (§2.5.5) Open addressing: the colliding item is placed in a different cell of the table Linear probing handles collisions by placing the colliding item in the next (circularly) available table cell Each table cell inspected is referred to as a “probe” Colliding items lump together, causing future collisions to cause a longer sequence of probes Example: h(x)  x mod 13 Insert keys 18, 41, 22, 44, 59, 32, 31, 73, in this order 0123456789101112 41 18445932223173 0123456789101112

38 Elementary Data Structures38 Search with Linear Probing Consider a hash table A that uses linear probing findElement (k) We start at cell h(k) We probe consecutive locations until one of the following occurs  An item with key k is found, or  An empty cell is found, or  N cells have been unsuccessfully probed Algorithm findElement(k) i  h(k) p  0 repeat c  A[i] if c   return NO_SUCH_KEY else if c.key ()  k return c.element() else i  (i  1) mod N p  p  1 until p  N return NO_SUCH_KEY

39 Elementary Data Structures39 Updates with Linear Probing To handle insertions and deletions, we introduce a special object, called AVAILABLE, which replaces deleted elements removeElement (k) We search for an item with key k If such an item (k, o) is found, we replace it with the special item AVAILABLE and we return element o Else, we return NO_SUCH_KEY insert Item (k, o) We throw an exception if the table is full We start at cell h(k) We probe consecutive cells until one of the following occurs  A cell i is found that is either empty or stores AVAILABLE, or  N cells have been unsuccessfully probed We store item (k, o) in cell i

40 Elementary Data Structures40 Double Hashing Double hashing uses a secondary hash function d(k) and handles collisions by placing an item in the first available cell of the series (i  jd(k)) mod N for j  0, 1, …, N  1 The secondary hash function d ( k ) cannot have zero values The table size N must be a prime to allow probing of all the cells Common choice of compression map for the secondary hash function: d 2 ( k )  q  k mod q where q  N q is a prime The possible values for d 2 ( k ) are 1, 2, …, q

41 Elementary Data Structures41 Consider a hash table storing integer keys that handles collision with double hashing N  13 h(k)  k mod 13 d(k)  7  k mod 7 Insert keys 18, 41, 22, 44, 59, 32, 31, 73, in this order Example of Double Hashing 0123456789101112 31 41 183259732244 0123456789101112

42 Elementary Data Structures42 Performance of Hashing In the worst case, searches, insertions and removals on a hash table take O(n) time The worst case occurs when all the keys inserted into the dictionary collide The load factor   n  N affects the performance of a hash table Assuming that the hash values are like random numbers, it can be shown that the expected number of probes for an insertion with open addressing is 1  (1   ) The expected running time of all the dictionary ADT operations in a hash table is O(1) In practice, hashing is very fast provided the load factor is not close to 100% Applications of hash tables: small databases compilers browser caches

43 Elementary Data Structures43 Universal Hashing (§ 2.5.6) A family of hash functions is universal if, for any 0<i,j<M-1, Pr(h(j)=h(k)) < 1/N. Choose p as a prime between M and 2M. Randomly select 0<a<p and 0<b<p, and define h(k)=(ak+b mod p) mod N Theorem: The set of all functions, h, as defined here, is universal.

44 Elementary Data Structures44 Proof of Universality (Part 1) Let f(k) = ak+b mod p Let g(k) = k mod N So h(k) = g(f(k)). f causes no collisions: Let f(k) = f(j). Suppose k<j. Then So a(j-k) is a multiple of p But both are less than p So a(j-k) = 0. I.e., j=k. (contradiction) Thus, f causes no collisions.

45 Elementary Data Structures45 Proof of Universality (Part 2) If f causes no collisions, only g can make h cause collisions. Fix a number x. Of the p integers y=f(k), different from x, the number such that g(y)=g(x) is at most Since there are p choices for x, the number of h’s that will cause a collision between j and k is at most There are p(p-1) functions h. So probability of collision is at most Therefore, the set of possible h functions is universal.


Download ppt "Elementary Data Structures Stacks, Queues, Lists, Vectors, Sequences, Trees, Priority Queues, Heaps, Dictionaries & Hash Tables."

Similar presentations


Ads by Google