11 Map ADTs  Map concepts  Map applications  A map ADT: requirements, contract.  Implementations of maps: using key-indexed arrays, entry arrays, linked-lists,

Slides:



Advertisements
Similar presentations
Chapter 7. Binary Search Trees
Advertisements

Linear Lists – Array Representation
AITI Lecture 19 Linked List Adapted from MIT Course 1.00 Spring 2003 Lecture 26 and Tutorial Note 9 (Teachers: Please do not erase the above note)
1 Symbol Tables Chapter Sedgewick. 2 Symbol Tables Searching Searching is a fundamental element of many computational tasks looking up a name.
12 Hash-Table Data Structures  Hash-table principles  Searching  Insertion  Deletion  Hash-table design  Implementations of sets and maps using hash-tables.
6-1 6 Stack ADTs Stack concepts. Stack applications. A stack ADT: requirements, contract. Implementations of stacks: using arrays, linked lists. Stacks.
Queue ADTs Queue concepts. Queue applications. A queue ADT: requirements, contract. Implementations of queues: using arrays, linked lists.
7 Queue ADTs  Queue concepts  Queue applications  A queue ADT: requirements, contract  Implementations of queues: using arrays and linked-lists  Queues.
9-1 9 Queue ADTs Queue concepts. Queue applications. A queue ADT: requirements, contract. Implementations of queues: using arrays, linked lists. Queues.
7-1 7 Queue ADTs Queue concepts. Queue applications. A queue ADT: requirements, contract. Implementations of queues: using arrays, linked lists. Queues.
Priority Queues. 2 Priority queue A stack is first in, last out A queue is first in, first out A priority queue is least-first-out The “smallest” element.
Dictionaries Chapter Chapter Contents Specifications for the ADT Dictionary Entries and methods Using the ADT Dictionary English Dictionary Telephone.
8 List and Iterator ADTs  List concepts  List applications  A list ADT: requirements, contract  Iterators  Implementations of lists: using arrays.
InOrder Traversal Algorithm // InOrder traversal algorithm inOrder(TreeNode n) { if (n != null) { inOrder(n.getLeft()); visit(n) inOrder(n.getRight());
CSE 373 Data Structures and Algorithms Lecture 18: Hashing III.
© 2006 Pearson Addison-Wesley. All rights reserved13 B-1 Chapter 13 (excerpts) Advanced Implementation of Tables CS102 Sections 51 and 52 Marc Smith and.
CSE 143 Lecture 7 Sets and Maps reading: ; 13.2 slides created by Marty Stepp
Java's Collection Framework
Maps A map is an object that maps keys to values Each key can map to at most one value, and a map cannot contain duplicate keys KeyValue Map Examples Dictionaries:
Set, TreeSet, TreeMap, Comparable, Comparator. Def: The abstract data type set is a structure that holds objects and satifies ARC: Objects can be added.
CS-2851 Dr. Mark L. Hornick 1 Tree Maps and Tree Sets The JCF Binary Tree classes.
Geoff Holmes and Bernhard Pfahringer COMP206-08S General Programming 2.
1 Hash Tables  a hash table is an array of size Tsize  has index positions 0.. Tsize-1  two types of hash tables  open hash table  array element type.
CM0551 Exam Prep. What are an algorithm’s time and space complexity? (2 marks) Answer: The growth rate of the algorithm’s time requirement and the computer.
CS212: DATA STRUCTURES Lecture 10:Hashing 1. Outline 2  Map Abstract Data type  Map Abstract Data type methods  What is hash  Hash tables  Bucket.
6 Stack ADTs  Stack concepts  Stack applications  Stack ADTs: requirements, contracts  Implementations of stacks: using arrays and linked-lists  Stacks.
1 Sets and Maps Starring: keySet Co-Starring: Collections.
D ESIGN & A NALYSIS OF A LGORITHM 07 – M AP Informatics Department Parahyangan Catholic University.
Information and Computer Sciences University of Hawaii, Manoa
24/3/00SEM107 - © Kamin & ReddyClass 16 - Searching - 1 Class 16 - Searching r Linear search r Binary search r Binary search trees.
2-1 Week 2 Sets Set concepts (you should know these!) Set applications. A set ADT (abstract data type): requirements, contract. Implementations of sets:
Tree ADTs Tree concepts. Applications of Trees. A Tree ADT – requirements, contract. Linked implementation of Trees. Binary Tree ADTs. Binary Search.
© 2006 Pearson Addison-Wesley. All rights reserved13 B-1 Chapter 13 (continued) Advanced Implementation of Tables.
CSS446 Spring 2014 Nan Wang.  Java Collection Framework ◦ Set ◦ Map 2.
7.2 Priority Queue ADTs Priority queue concepts
Hash Tables1   © 2010 Goodrich, Tamassia.
CS 206 Introduction to Computer Science II 02 / 13 / 2009 Instructor: Michael Eckmann.
Topic 1 Object Oriented Programming. 1-2 Objectives To review the concepts and terminology of object-oriented programming To discuss some features of.
© 2004 Goodrich, Tamassia Hash Tables1  
10 Binary-Search-Tree Data Structure  Binary-trees and binary-search-trees  Searching  Insertion  Deletion  Traversal  Implementation of sets using.
Sets and Maps Computer Science 4 Mr. Gerb Reference: Objective: Understand the two basic applications of searching.
Building Java Programs Bonus Slides Hashing. 2 Recall: ADTs (11.1) abstract data type (ADT): A specification of a collection of data and the operations.
1 Introduction  Algorithms  Data structures  Abstract data types  Programming with lists and sets © 2008 David A Watt, University of Glasgow Algorithms.
9-1 9 Set ADTs Set concepts. Set applications. A set ADT: requirements, contract. Implementations of sets: using arrays, linked lists, boolean arrays.
Copyright © 0 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Starting Out with Java From Control Structures through Data Structures by Tony.
Week 10 - Friday.  What did we talk about last time?  Graph representations  Adjacency matrix  Adjacency lists  Depth first search.
Hash Tables From “Algorithms” (4 th Ed.) by R. Sedgewick and K. Wayne.
Review Sorting algorithms Selection Sort Insertion Sort Bubble Sort Merge Sort Quick Sort.
Week 15 – Wednesday.  What did we talk about last time?  Review up to Exam 1.
9 Set ADTs  Set concepts  Set applications  A set ADT: requirements, contract  Implementations of sets: using member arrays, linked lists, boolean.
Maps Nick Mouriski.
JAVA: An Introduction to Problem Solving & Programming, 6 th Ed. By Walter Savitch ISBN © 2012 Pearson Education, Inc., Upper Saddle River,
© 2005 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved. Data Structures for Java William H. Ford William R. Topp Chapter 20 Ordered.
1 the BSTree class  BSTreeNode has same structure as binary tree nodes  elements stored in a BSTree are a key- value pair  must be a class (or a struct)
CSE 143 Lecture 11: Sets and Maps reading:
3-1 Java's Collection Framework Another use of polymorphism and interfaces Rick Mercer.
(c) University of Washington20c-1 CSC 143 Binary Search Trees.
11 Map ADTs Map concepts. Map applications.
Design & Analysis of Algorithm Map
Efficiency of in Binary Trees
slides created by Marty Stepp and Hélène Martin
CSE 373: Data Structures and Algorithms
slides adapted from Marty Stepp and Hélène Martin
CSE 373 Data Structures and Algorithms
CSE 373: Data Structures and Algorithms
CS210- Lecture 16 July 11, 2005 Agenda Maps and Dictionaries Map ADT
Trees in java.util A set is an object that stores unique elements
slides created by Marty Stepp and Hélène Martin
8 List ADTs List concepts. List applications.
Presentation transcript:

11 Map ADTs  Map concepts  Map applications  A map ADT: requirements, contract.  Implementations of maps: using key-indexed arrays, entry arrays, linked-lists, BSTs  Maps in the Java class library © 2008 David A Watt, University of Glasgow Algorithms & Data Structures (M)

11-2 Map concepts (1)  A map is a collection of entries, in no fixed order, in which all entries have distinct keys.  Each entry is a tuple that consists of a key field and a value field. More generally, an entry is a tuple consisting of one or more key fields and one or more value fields.

11-3 Example: maps  Map with (letter, value) entries:  Maps with (country, currency) entries: lettervalue I1 V5 X10 L50 C100 D500 M1000 Roman = NAFTA = countrycurrency CAdollar USdollar MXpeso countrycurrency DEeuro FReuro ITeuro UKpound DKkrone ESeuro EU = key field value field

11-4 Map concepts (2)  The size (or cardinality) of a map m is the number of entries in m. This is written #m. E.g.: #NAFTA = 3  An empty map has no entries.  We can lookup a map for a given key, to obtain the corresponding value (if any). E.g.: looking up NAFTA for US gives “dollar” looking up NAFTA for UK gives nothing

11-5 Map concepts (3)  We can overlay map m 1 by map m 2. The result contains all entries from both m 1 and m 2, except that where both maps contain entries with the same key, the result contains the entry from m 2 only. E.g.: count1 = count2 = Result of overlaying count1 by count2 = statewinner New YorkGore TexasBush FloridaGore statewinner OhioBush FloridaBush statewinner New YorkGore TexasBush OhioBush FloridaBush

11-6 Map applications (1)  Relational database (RDB): –An RDB table is a collection of tuples, in no particular order. –If an RDB table has a key field, all tuples must have distinct keys. So an RDB relation with a key field is in fact a map.

11-7 Map applications (2)  Phone book: –Each entry consists of a name, address, and phone number. –Several entries may share the same name or the same address, but each entry must have a unique name-and- address combination. –The entries could be in any order. (They are typically sorted by name and address, to make lookup fast, but that is not essential.) –Thus a phone book is a map in which the key field is the name-and-address combination.

11-8 Map ADT: requirements  Requirements: 1)It must be possible to make a map empty. 2)It must be possible to test whether a map is empty. 3)It must be possible to test whether a map contains an entry with a given key. 4)It must be possible to look up the value corresponding to a given key in a map. 5)It must be possible to add a new entry to a map or to replace an existing entry. 6)It must be possible to remove an entry from a map, given its key. 7)It must be possible to test whether two maps are equal. 8)It must be possible to compute the overlay of two maps. 9)It must be possible to traverse a map.

11-9 Map ADT: contract (1)  Possible contract for homogeneous maps: public interface Map { // Each Map object is a homogeneous map // whose keys and values are of types K and V // respectively. //////////// Accessors //////////// public boolean isEmpty (); // Return true if and only if this map is empty. public int size (); // Return the size of this map.

11-10 Map ADT: contract (2)  Possible contract (continued): public V get (K key); // Return the value in the entry with key in this map, // or null if there is no such entry. public boolean equals (Map that); // Return true if this map is equal to that. public Set keySet (); // Return the set of all keys in this map. //////////// Transformers //////////// public void clear (); // Make this map empty.

11-11 Map ADT: contract (3)  Possible contract (continued): public V remove (K key); // Remove the entry with key (if any) from this map. // Return the value in that entry, or null if there was // no such entry. public V put (K key, V val); // Add the entry ( key, val ) to this map, replacing any // existing entry whose key is key. Return the value in // that entry, or null if there was no such entry. public void putAll (Map that); // Overlay this map with that, i.e., add all entries of // that to this map, replacing any existing entries // with the same keys. }

11-12 Implementation of small-integer-key maps using key-indexed arrays (1)  If the keys are known to be small integers, in the range 0…m–1, represent the map by: –an array vals of length m, such that vals[k] contains a value v if and only if (k, v) is a entry of the map. 01m–1 Invariant: value? 2 Empty map: 01m–12

11-13 Implementation of small-integer-key maps using key-indexed arrays (2) Illustration (m = 20): codemodule 01CS1 02CS2 10DB 11OOP 12ADS 14OS 16HCI CS1CS OOPADSOSDB HCI is represented by

11-14 Implementation of small-integer-key maps using key-indexed arrays (3)  Summary of algorithms and time complexities: OperationAlgorithmTime complexity get inspect array elementO(1) remove make array element nullO(1) put update array elementO(1) putAll pairwise update all array elementsO(m)O(m) equals pairwise equality testO(m)O(m)

11-15 Implementation of maps using entry arrays (1)  Represent a bounded map (size  cap) by: –a variable size –an array entries of length cap, containing the map entries in entries[0…size–1], which is kept sorted by key. Empty map: 1 size=0 cap–1 01size–1size Invariant: key cap–1 val key val key val least key greatest key

11-16 Implementation of maps using entry arrays (2) elementnumber He2 Ne10 Ar18 Kr36 Xe54 Rn86 Illustration (cap = 9): is represented by 45 Xe54Rn86 size=67 23 Ne10Kr36 01 He2Ar18 8

11-17 Implementation of maps using entry arrays (3)  Summary of algorithms and time complexities: OperationAlgorithmTime complexity get binary searchO(log n) remove binary search, then array deletionO(n)O(n) put binary search, then array insertionO(n)O(n) putAll variant of array mergeO(n+n') equals pairwise equality testO(n') where n' is the size of the 2 nd map

11-18 Implementation of maps using SLLs (1)  Represent an (unbounded) map by: –a variable size –an SLL, containing one entry per node, which is kept sorted by key. Empty map: 0 Invariant: key val n least key greatest key

11-19 Implementation of maps using SLLs (2) elementnumber He2 Ne10 Ar18 Kr36 Xe54 Rn86 Illustration: is represented by Xe54Rn86Ne10Kr36He2Ar 18 6

11-20 Implementation of maps using SLLs (3)  Summary of algorithms and time complexities: OperationAlgorithmTime complexity get SLL linear searchO(n)O(n) remove SLL linear search, then deletionO(n)O(n) put SLL linear search, then insertionO(n)O(n) putAll variant of SLL mergeO(n+n') equals pairwise equality testO(n')

11-21 Implementation of maps using BSTs (1)  Represent an (unbounded) map by: –a variable size –a BST, containing one entry per node, in which the entries are ordered by their keys. Invariant: BST n Empty map: 0

11-22 Implementation of maps using BSTs (2) elementnumber He2 Ne10 Ar18 Kr36 Xe54 Rn86 Illustration: could be represented by Xe54 Rn86 Ne10 Kr36 He2 Ar18 6

11-23 Implementation of maps using BSTs (3)  Summary of algorithms and time complexities: OperationAlgorithmTime complexity bestworst get BST searchO(log n)O(n) remove BST deletionO(log n)O(n) put BST insertionO(log n)O(n) putAll BST mergeO(n' log(n+n'))O(n'n) equals traversal of 2 nd BST comb- ined with search of 1 st BST O(n' log n)O(n'n)

11-24 Summary of map implementations OperationKey-indexed array repr- esentation Entry array represent- ation SLL repr- esentation BST representation bestworst get O(1)O(log n)O(n)O(n)O(log n)O(n) remove O(1)O(n)O(n)O(n)O(n)O(log n)O(n) put O(1)O(n)O(n)O(n)O(n)O(log n)O(n) putAll O(m)O(m)O(n+n') O(n'log(n+n'))O(n'n) equals O(m)O(m)O(n') O(n'log n)O(n'n)

11-25 Maps in the Java class library  The library interface java.util.Map is similar to the above interface Map.  The library class java.util.TreeMap implements java.util.Map, representing each map by a search-tree (actually a red-black tree).  The library class java.util.HashMap implements java.util.Map, representing each map by a hash-table (§12).

11-26 Example: mobile phone contacts (1)  Consider a simple mobile phone equipped with a keypad, display, and non-volatile memory.  The memory contains a table of contacts. Each entry consists of a contact’s name and phone number. All names must be distinct.  The mobile phone enables the user to: –add a new contact, by entering the contact’s name and phone number –display the contacts’ names, one by one –make a call to the currently displayed contact –remove the currently displayed contact.

11-27 Example: mobile phone contacts (2)  Implementation outline: public class MobilePhone { private Map contacts; // This is the table of contacts. Each entry consists of // a name and a phone number (both strings). private Iterator names; private String currentName = "???"; public MobilePhone () { contacts = new TreeMap (); }

11-28 Example: mobile phone contacts (3)  Implementation outline (continued): public void addContact () { // Add a new contact, consisting of a name and // phone number entered by the user. String newName = Keypad.readName(); String newNum = Keypad.readNumber(); String oldNum = contacts.get(newName); if (oldNum != null) { … // Check whether the user really wants to // replace the existing entry. If not, return. } contacts.put(newName, newNum); }

11-29 Example: mobile phone contacts (4)  Implementation outline (continued): public void displayFirstContact () { // Display the first contact’s name. names = contacts.keySet().iterator(); displayNextContact(); } public void displayNextContact () { // Display the next contact’s name. if (names.hasNext()) currentName = names.next(); else currentName = "???"; Display.write(currentName); }

11-30 Example: mobile phone contacts (5)  Implementation outline (continued): public void callContact () { // Make a call to the currently displayed contact. String num = contacts.get(currentName); if (num != null) { Display.write(num); … // Make a call to num. } }

11-31 Example: mobile phone contacts (6)  Implementation outline (continued): public void removeContact () { // Remove the currently displayed contact. contacts.remove(currentName); } }