Assignment 3 Biggest deductions No decomposition

Slides:



Advertisements
Similar presentations
Comp 122, Spring 2004 Binary Search Trees. btrees - 2 Comp 122, Spring 2004 Binary Trees  Recursive definition 1.An empty tree is a binary tree 2.A node.
Advertisements

1 abstract containers hierarchical (1 to many) graph (many to many) first ith last sequence/linear (1 to 1) set.
Fall 2007CS 2251 Trees Chapter 8. Fall 2007CS 2252 Chapter Objectives To learn how to use a tree to represent a hierarchical organization of information.
1 abstract containers hierarchical (1 to many) graph (many to many) first ith last sequence/linear (1 to 1) set.
CSCE 3110 Data Structures & Algorithm Analysis Binary Search Trees Reading: Chap. 4 (4.3) Weiss.
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.
Stacks & Recursion. Stack pushpop LIFO list - only top element is visible top.
Searching: Binary Trees and Hash Tables CHAPTER 12 6/4/15 Nyhoff, ADTs, Data Structures and Problem Solving with C++, Second Edition, © 2005 Pearson Education,
Spring 2010CS 2251 Trees Chapter 6. Spring 2010CS 2252 Chapter Objectives Learn to use a tree to represent a hierarchical organization of information.
Computer Science Department Data Structure & Algorithms Lecture 8 Recursion.
Week 8 - Wednesday.  What did we talk about last time?  Level order traversal  BST delete  2-3 trees.
Week 10 - Friday.  What did we talk about last time?  Graph representations  Adjacency matrix  Adjacency lists  Depth first search.
Prof. Amr Goneid, AUC1 CSCE 210 Data Structures and Algorithms Prof. Amr Goneid AUC Part 6. Dictionaries(3): Binary Search Trees.
CISC220 Fall 2009 James Atlas Dec 07: Final Exam Review.
Week 15 – Wednesday.  What did we talk about last time?  Review up to Exam 1.
1 i206: Lecture 12: Hash Tables (Dictionaries); Intro to Recursion Marti Hearst Spring 2012.
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)
1 Binary Search Trees. 2 Binary Search Trees Binary Search Trees The Binary Search Tree (BST) Search, Insertion and Traversal of BST Removal of nodes.
Final Exam Review CS 3358.
CSCE 210 Data Structures and Algorithms
CSC317 Selection problem q p r Randomized‐Select(A,p,r,i)
CSCE 210 Data Structures and Algorithms
12 Collections Software Solutions Lewis & Loftus java 5TH EDITION
Non Linear Data Structure
Data Structures and Design in Java © Rick Mercer
Trees Chapter 15.
COMP 53 – Week Fourteen Trees.
CSCE 3110 Data Structures & Algorithm Analysis
CSCE 3110 Data Structures & Algorithm Analysis
Week 7 - Friday CS221.
Multiway Search Trees Data may not fit into main memory
Data Structure Interview Question and Answers
CS Data Structures Chapter 8 Lists Mehmet H Gunes
DATA STRUCTURES AND OBJECT ORIENTED PROGRAMMING IN C++
Dr. Bernard Chen Ph.D. University of Central Arkansas
UNIT III TREES.
Homework 4 questions???.
Data Structures Interview / VIVA Questions and Answers
Cinda Heeren / Geoffrey Tien
Lecture 22 Binary Search Trees Chapter 10 of textbook
B+ Tree.
Array Array is a variable which holds multiple values (elements) of similar data types. All the values are having their own index with an array. Index.
Week 11 - Friday CS221.
Hashing Exercises.
abstract containers sequence/linear (1 to 1) hierarchical (1 to many)
COMP 103 Binary Search Trees.
ITEC 2620M Introduction to Data Structures
Tree data structure.
i206: Lecture 13: Recursion, continued Trees
Binary Search Trees Why this is a useful data structure. Terminology
Binary Trees, Binary Search Trees
Chapter 22 : Binary Trees, AVL Trees, and Priority Queues
Map interface Empty() - return true if the map is empty; else return false Size() - return the number of elements in the map Find(key) - if there is an.
What remains Topics Assignments Final exam
structures and their relationships." - Linus Torvalds
CMSC 341 Lecture 10 B-Trees Based on slides from Dr. Katherine Gibson.
Hash table another data structure for implementing a map or a set
original list {67, 33,49, 21, 25, 94} pass { } {67 94}
structures and their relationships." - Linus Torvalds
Tree data structure.
CMSC 202 Trees.
CS6045: Advanced Algorithms
Advanced Implementation of Tables
Pointers & Dynamic Data Structures
DATA STRUCTURE.
EE 312 Final Exam Review.
Data Structures and Algorithms Memory allocation and Dynamic Array
Recursion.
structures and their relationships." - Linus Torvalds
Presentation transcript:

Assignment 3 Biggest deductions No decomposition No Comments describing behavior of stack methods Stack class needs to be usable in any application requiring stack behavior Needs guards (#ifnotdef ----) Use typedef Needs a peek method

Assignment 4?

Zybook assignment before class on Thursday Ch.17 - recursion

Ways in which elements of a container class can be related to each other Linear (1 - to - 1) Each element has a predecessor and a successor First element has no predecessor, last element has no successor Hierarchical (1 – to – many) Each element has one predecessor and 0 to multiple successors One element (the root) has no predecessor Graph (many to many) Each element has 0 to many predecessors and 0 to many successors Membership Elements do not have predecessors or successors Elements are related by membership only

Two Adts that store a collection of items that have no relationship other than membership

Set and map Both are value oriented Both have operations to Add an element Remove an element Find out if an element is a member of the collection Both can be implemented using the same data structures

set interface Empty() - return true if set is empty; else return false Size() - return the number of elements in the set Find(element) - return true if this element is In the set; else return false Add(element) – if this element is not in the set, add it to the set and return true; else return false Remove(element) – if this element is in the set, remove it and return true; else return false

Some examples of a set words that appear in a document Each word in the document is a member of the set ip addresses that are known to be spammers Ip addresses can be added to and removed from the set Set of prime numbers

How is a map different from a set? a map stores elements that are key-value pairs Key is unique identifier Value is other information about the element

Some examples of a map Concordance Turkish to English dictionary Key – a word Value – number of times the word appears in a document Turkish to English dictionary Key – Turkish word Value – the English word Users of a computer system Key – user id Value – password and other information Collection of bank accounts Key – account number Value – balance and other information

Map interface Empty() - return true if the map is empty; else return false Size() - return the number of elements in the map Find(key) - if there is an element with this key return true; else return false Add(key, value) – if there is no element with this key, add it to the map and return true; else return false Remove(key) – if there is an element with this key, remove it from the map and return true; else return false Retrieve(key) – if there is an element with this key, return the value; else return null

How does a map differ from a set? Map elements consist of a key and a value Map has a retrieve method Given a key return the associated value In many applications a value is retrieved in order to modify it Ex: deposit or withdraw from a bank account Ex: let a user change her password

Dealing with key-value pair Use Typedef for itemtype Itemtype consists of a key and a value Need Typedef for keytype Need Typedef for valuetype Could write our own class that encapsulates a key and a value Instead will use a template class from the C++ standard library pair<T1, T2>

Pair<T1, T2> A template class defined in <utility> The class pair has 2 public data members First Second Use first for the key Use second for the value

Some pair<t1, t2> operations Constructor Pair<string, int> mypair(“some string”, 36); Make_pair(v1, v2) Returns a pair made from v1 and v2 Pair<string, int> yourpair = Make_pair(“another string”, 27); What is the value of mypair.second yourPair.first

example of using pair<T1, T2> #include<iostream> #include<utility> using namespace std; typedef string KeyType; typedef string ValueType; typedef pair<KeyType, ValueType> ItemType; int main(){ ItemType list[3]; // an array of key-value pairs list[0] = make_pair("John Smith","123-234-1234"); list[1] = make_pair("Jane Smith","123-234-1234"); list[2] = make_pair("Bill Jones","456-556-3265"); for(int i = 0; i < 3; i++){ cout << list[i].first << " has the phone number: " << list[i].second << endl; } /* John Smith has the phone number: 123-234-1234 Jane Smith has the phone number: 123-234-1234 Bill Jones has the phone number: 456-556-3265 */ example of using pair<T1, T2>

Changing an item stored in a container List method retrieve(i) returns the item at position I Map method retrieve(key) returns the value associated with key Suppose we retrieve an item in order to modify it Retrieve a bankaccount from a map in order make a Deposit or withdrawal Retrieve an itemtopurchase from a list in order to change the quantity

What will happen? ShopingCart myCart; // add some items to myCart // including 3 pencils at position 2 ItemType item = myCart.retrieve(2); item.setQuantity(5); ----- item = myCart.retrieve(2); cout << item.getQuantity() << endl;

Why?

A solution Have retrieve return by reference Valuetype& retrieve(key Keytype) Itemtype& retrieve (pos int) Would then need: ShopingCart myCart; // add some items to myCart // including 3 pencils at position 2 ItemType item = myCart.retrieve(2); mycart.retrieve(2).setquantity(5); item.setQuantity(5); ----- item = myCart.retrieve(2); cout << item.getQuantity() << endl;

Another solution Both user and implementor of a list need to have access to the same item Both need a pointer to the same block of memory Define itemtype as a pointer to itemtype Typedef itemtopurchase* itemtype Would then need: ShopingCart myCart; // add some items to myCart // ex: mycart.append(new itemtopurchase(-----,-----,-----); // including 3 pencils at position 2 ItemType item = myCart.retrieve(2); item->setQuantity(5); ----- item = myCart.retrieve(2); cout << item->getQuantity() << endl;

Is Jane Smith’s phone number changed? #include<iostream> #include<utility> using namespace std; typedef string KeyType; typedef string ValueType; typedef pair<KeyType, ValueType> ItemType; int main(){ ItemType list[3]; // an array of key-value pairs list[0] = make_pair("John Smith","123-234-1234"); list[1] = make_pair("Jane Smith","123-234-1234"); list[2] = make_pair("Bill Jones","456-556-3265"); ValueType phoneNumber = list[1].second; phoneNumber = “333-424-6385”; for(int i = 0; i < 3; i++){ cout << list[i].first << " has the phone number: " << list[i].second << endl; } Is Jane Smith’s phone number changed?

Define ValueType as a pointer to string #include<iostream> #include<utility> using namespace std; typedef string KeyType; typedef string* ValueType; typedef pair<KeyType, ValueType> ItemType; int main(){ ItemType list[3]; // an array of key-value pairs list[0] = make_pair("John Smith", new string("123-234-1234")); list[1] = make_pair("Jane Smith", new string("123-234-1234“)); list[2] = make_pair("Bill Jones", new string("456-556-3265")); ValueType phoneNumber = list[1].second; *phoneNumber = “333-424-6385”; for(int i = 0; i < 3; i++){ cout << list[i].first << " has the phone number: " << *list[i].second << endl; } Define ValueType as a pointer to string

What if there is nothing to retrieve? Retrieve(key) – if there is an item with this key, return the value; else return null Since value is a pointer to the associated value Application can now change the value as needed Return value of null means there is no item with that key

Another issue What happens when a node is returned to the heap? By remove By the destructor By operator= Delete p; P

Whose job is it to return the space allocated for the value? One option: Do it in the map class Delete p->element.second before deleting p General rule: allocator of memory space should return it Application program created the element (including allocating heap memory space for the value) C++11 provides 3 kinds of “smart” pointers will look at the type shared_ptr

Shared_ptr An object stored in the heap can be pointed to by multiple pointers If the pointers are “raw” pointers When this object is not accessible by any pointer it becomes “garbage” If the pointers are of type shared_ptr When this object is not accessible by any shared_ptr it is automatically returned to the heap Made possible by a technique known as reference counting An object knows how many pointers can access it

The basic idea – raw pointers a raw_ptr a dynamically created object a raw_ptr a raw_ptr

The basic idea – shared pointers a shared_ptr a dynamically created object a shared_ptr reference count is 3 a shared_ptr

#include<iostream> #include<vector> #include<string> using namespace std; int main() { vector<string*> v; v.push_back(new string("abc")); v.push_back(new string("def")); v.push_back(new string("ghi")); } /* remote03:~/2017/Trials> valgrind ./a.out ------------------------------- ==4804== HEAP SUMMARY: ==4804== in use at exit: 108 bytes in 6 blocks ==4804== total heap usage: 9 allocs, 3 frees, 164 bytes allocated remote03:~/2017/Trials> */

#include<iostream> #include<vector> #include<string> #include<memory> using namespace std; int main() { vector<shared_ptr<string>> v; v.push_back(make_shared<string>("abc")); v.push_back(make_shared<string>("def")); v.push_back(make_shared<string>("ghi")); } /* remote03:~/2017/Trials> valgrind ./a.out ------------------------------- ==4879== HEAP SUMMARY: ==4879== in use at exit: 0 bytes in 0 blocks ==4879== total heap usage: 9 allocs, 9 frees, 268 bytes allocated ==4879== All heap blocks were freed -- no leaks are possible remote03:~/2017/Trials> */

Possible map data structures?

Value oriented list data structure add find remove retrieve vector (unordered) vector (ordered by key) linked list (unordered) linked list (ordered by key)

Some map data structures data structure add find remove retrieve array (unordered) O(n)* O(n) O(n) O(n) array (ordered by key) O(n) O(log2 n) O(n) O(log2 n) linked list (unordered) O(n)* O(n) O(n) O(n) linked list (ordered by key) O(n) O(n) O(n) O(n) * need to make sure key is unique

Can we do better? Self-organizing list Search trees Hash table Add: put at end of a linked list (if not a duplicate key) – O(n) Find and retrieve: linear search and then move element to the beginning of the linked list – O(n) Remove: linear search and then remove – O(n) Search trees Binary search tree Add, find, retrieve and remove all O(log2 n) in the average case, but O(n) in the worst case Balanced search trees Guarantee O(log2 n) add, find, retrieve and remove AVL tree Red-black tree treap Hash table Add, find, retrieve and remove all O(1) but actual performance depends on hash function and load factor

Assignment 5 Define and implement a map Will be a subclass of the abstract class MapInterface Mapinterface is defined in mapinterface.h Use a value-oriented linked list as the implementation data structure store items sorted by key store items unsorted Self-organizing list

M A P I N T E R F C Your map tester Map implementation My map tester

Looking ahead Next assignment will have same organization as assignment 5 Will implement the map interface using a binary search tree as the data structure

Zybook assignment before class on Tuesday march 20 do Ch Zybook assignment before class on Tuesday march 20 do Ch.19 – binary search trees

binary search tree A binary search tree is a binary tree that has the bst property Each node holds a value Its left child is either empty or holds a smaller value Its right child is either empty or holds a larger value 45 36 56 42 25 52 60 30 50

Some binary tree terminology Parent - predecessor of an item Child - successor of an item A child is either a left child or a right child Path - route from one node to another node There is a unique path from the root to each node Leaf - node with no successors Level - root is at level 0, root’s successors are at level 1, etc. Height - length of the longest path 45 36 56 42 25 52 60 30 50

Bsts can be defined recursively A Bst is either empty or Consists of a root which has A left child which is a bst A right child which is bst

recursion A function that calls itself is a recursive function Especially useful when dealing with algorithms and data structures that can be defined recursively Recursion is an alternative to a loop May be simpler to write May be slower to execute May take more memory space Is a tool that programmers should know how and when to use

Outline of a recursive function returnType recFunc (parameters) { if (answer is known) //the base case return answer else //the recursive case call recFunc to solve a smaller version of the same problem

Computing n! Non-recursive definition Non-recursive function fact(0) = 1 fact(n) = n * (n-1) * (n-2) * …. * 1 (for n > 0) Non-recursive function int fact(int n) { assert(n >= 0); int answer = 1; for(int i = n; i > 0; i--) answer = answer * i; return answer; }

Computing n! Recursive definition Recursive function fact(0) = 1 (base case) fact(n) = n * fact(n-1) for n>0 (recursive case) Recursive function ??????

int recFact(int n) { assert(n >= 0); if (n == 0) return 1; else return n * recFact(n – 1); }

How recursion works every function call results in an activation record being pushed onto the run-time stack holds values for parameters, local variables, etc. as a recursive function is executing there are multiple activation records for that function on the stack activation records are popped from the stack as each recursive call returns to its caller

factorial = recFact(4); main recfact n factorial n ? Run-time stack 4 3 n 2 1

Unwinding the recursion main recfact n factorial n 24 returns 4 * 6 returns 3 * 2 returns 2 * 1 returns 1 * 1 returns 1 4 3 n 2 1

When to use recursion? some languages (Lisp) have no loops recursion is the only way to cause iteration/repetition there are no problems that can only be solved recursively what to consider in deciding between recursion and a loop which leads to an easier to understand solution? are there multiple recursive calls in the recursive solution? binary search, quicksort is the data structure defined recursively? binary search tree does the recursive solution require recomputing values? finding the nth Fibonacci number how deep is the recursion? recursive solution could result in stack overflow