CPS 100 7.1 Recurrences l Summing Numbers int sum(int n) { if (0 == n) return 0; else return n + sum(n-1); } l What is complexity? justification? l T(n)

Slides:



Advertisements
Similar presentations
Stacks & Their Applications COP Stacks  A stack is a data structure that stores information arranged like a stack.  We have seen stacks before.
Advertisements

CPS 100, Spring Spirits of Linear Structures l Past, Present, Future, … l Linked-lists and arrays and ArrayLists  ADT: insert, delete, iterate/traverse,
Topic 15 Implementing and Using Stacks
CS102 – Data Structures Lists, Stacks, Queues, Trees, Hash Collections Framework David Davenport Spring 2002.
TCSS 342, Winter 2005 Lecture Notes
Topic 15 Implementing and Using Stacks
The Stack and Queue Types Lecture 10 Hartmut Kaiser
CPS 100, Spring Data Structures revisited l Linked lists and arrays and ArrayLists and …  Linear structures, operations include insert, delete,
Exam 1 –Monday June 25 th –open Book / Open Notes –No Electronic Devices (calculators, laptops, etc) –Room Number: W –Time: 5:30pm to 8:00pm.
CHAPTER 05 Compiled by: Dr. Mohammad Omar Alhawarat Stacks & Queues.
ISOM MIS 215 Module 3 – Stacks and Queues. ISOM Where are we? 2 Intro to Java, Course Java lang. basics Arrays Introduction NewbieProgrammersDevelopersProfessionalsDesigners.
CompSci 100 Prog Design and Analysis II October 14, 2010 Prof. Rodger CompSci 100, Fall
CPS 100, Spring Analysis: Algorithms and Data Structures l We need a vocabulary to discuss performance and to reason about alternative algorithms.
Information and Computer Sciences University of Hawaii, Manoa
COP3530 Data Structures600 Stack Stack is one the most useful ADTs. Like list, it is a collection of data items. Supports “LIFO” (Last In First Out) discipline.
CPS Data Structures revisited l Linked lists and arrays and ArrayLists and …  Linear structures, operations include insert, delete, traverse,
CompSci 100e Program Design and Analysis II March 29, 2011 Prof. Rodger CompSci 100e, Spring20111.
CPS Sequential search revisited l What does the code below do? How would it be called initially?  Another overloaded function search with 2 parameters?
CSE 373: Data Structures and Algorithms Lecture 1: Introduction; ADTs; Stacks; Eclipse.
CompSci 100E 9.1 Stack: What problems does it solve?  Stacks are used to avoid recursion, a stack can replace the implicit/actual stack of functions called.
CPS 100, Fall Catching Up, Moving ahead l Last week and this week  How did you study for the exam? Next time?  How can you/should you work with.
CompSci 100e Program Design and Analysis II March 15, 2011 Prof. Rodger CompSci 100e, Spring20111.
CS102 – Data Structures Lists, Stacks, Queues, Trees & HashTables. David Davenport.
Copyright © Curt Hill Stacks An Useful Abstract Data Type.
Lecture Objectives  To understand how Java implements a stack  To learn how to implement a stack using an underlying array or linked list  Implement.
CompSci 100E 15.1 What is a Binary Search?  Magic!  Has been used a the basis for “magical” tricks  Find telephone number ( without computer ) in seconds.
Compsci 100, Fall Analysis: Algorithms and Data Structures l We need a vocabulary to discuss performance  Reason about alternative algorithms.
CSCI 62 Data Structures Dr. Joshua Stough October 7, 2008.
CPS Review of Data Structures l We’ve studied concrete data structures/type (CDT)  Vectors Homogeneous aggregates supporting random access  Linked.
Stacks A stack is a linear data structure that can be accessed only at one of its ends for storing and retrieving data LIFO (Last In First Out) structure.
CPS Solving Problems Recursively l Recursion is an indispensable tool in a programmer’s toolkit  Allows many complex problems to be solved simply.
CompSci 100E 19.1 Getting in front  Suppose we want to add a new element  At the back of a string or an ArrayList or a …  At the front of a string.
CS-2851 Dr. Mark L. Hornick 1 Stacks and Queues Behavior vs. Structure.
CPS 100e 6.1 What’s the Difference Here? l How does find-a-track work? Fast forward?
CPS 100, Spring Tools: Solve Computational Problems l Algorithmic techniques  Brute-force/exhaustive, greedy algorithms, dynamic programming,
CompSci 100e 7.1 Plan for the week l Recurrences  How do we analyze the run-time of recursive algorithms? l Setting up the Boggle assignment.
Chapter 3 Lists, Stacks, Queues. Abstract Data Types A set of items – Just items, not data types, nothing related to programming code A set of operations.
CPS 100, Fall Linear Structures Revisited l Linked-lists and arrays and ArrayLists and …  Linear structures, operations include insert, delete,
Stacks and Queues. 2 Abstract Data Types (ADTs) abstract data type (ADT): A specification of a collection of data and the operations that can be performed.
Prefix notation in action
Stacks Access is allowed only at one point of the structure, normally termed the top of the stack access to the most recently added item only Operations.
Data Structure By Amee Trivedi.
Stacks Chapter 5.
Stack: What problems does it solve?
Marcus Biel, Software Craftsman
Analysis: Algorithms and Data Structures
Data Structures revisited
Chapter 15 Lists Objectives
Recap: Solution of Last Lecture Activity
Plan for Week Linear structures: Stack, Queue
Data Structures Interview / VIVA Questions and Answers
Tools: Solve Computational Problems
CSE 373: Data Structures and Algorithms
Algorithms and Data Structures
Stack Data Structure, Reverse Polish Notation, Homework 7
Introduction to Data Structures
Stacks and Queues.
structures and their relationships." - Linus Torvalds
Building Java Programs
structures and their relationships." - Linus Torvalds
Stacks and Queues.
Stacks, Queues, and Deques
Stack A data structure in which elements are inserted and removed only at one end (called the top). Enforces Last-In-First-Out (LIFO) Uses of Stacks Evaluating.
CS6045: Advanced Algorithms
Stacks.
Topic 15 Implementing and Using Stacks
CSC 143 Java Applications of Trees.
structures and their relationships." - Linus Torvalds
Stacks and Queues.
Presented by : Aman Gupta PGT CS KV No.1, Narimedu, Madurai
Presentation transcript:

CPS Recurrences l Summing Numbers int sum(int n) { if (0 == n) return 0; else return n + sum(n-1); } l What is complexity? justification? l T(n) = time to compute sum for n T(n) = T(n-1) + 1 T(0) = 1 l instead of 1, use O(1) for constant time  independent of n, the measure of problem size

CPS Solving recurrence relations l plug, simplify, reduce, guess, verify? T(n) = T(n-1) + 1 T(0) = 1 T(n) = T(n-k) + k find the pattern! Now, let k=n, then T(n) = T(0)+n = 1+n l get to base case, solve the recurrence: O(n) T(n-1) = T(n-1-1) + 1 T(n) = [T(n-2) + 1] + 1 = T(n-2)+2 T(n-2) = T(n-2-1) + 1 T(n) = [(T(n-3) + 1) + 1] + 1 = T(n-3)+3

CPS Complexity Practice l What is complexity of Build ? (what does it do?) ArrayList build(int n) { if (0 == n) return new ArrayList(); // empty ArrayList list = build(n-1); for(int k=0;k < n; k++){ list.add(new Integer(n)); } return list; } l Write an expression for T(n) and for T(0), solve.

CPS Recognizing Recurrences l Solve once, re-use in new contexts  T must be explicitly identified  n must be some measure of size of input/parameter T(n) is the time for quicksort to run on an n-element vector T(n) = T(n/2) + O(1) binary search O( ) T(n) = T(n-1) + O(1) sequential search O( ) T(n) = 2T(n/2) + O(1) tree traversal O( ) T(n) = 2T(n/2) + O(n) quicksort O( ) T(n) = T(n-1) + O(n) selection sort O( ) l Remember the algorithm, re-derive complexity n log n n log n n n2n2

CPS Stack: What problems does it solve? l Stacks are used to avoid recursion, a stack can replace the implicit/actual stack of functions called recursively l Stacks are used to evaluate arithmetic expressions, to implement compilers, to implement interpreters  The Java Virtual Machine (JVM) is a stack-based machine  Postscript is a stack-based language  Stacks are used to evaluate arithmetic expressions in many languages l Small set of operations: LIFO or last in is first out access  Operations: push, pop, top, create, clear, size  More in postscript, e.g., swap, dup, rotate, …

CPS Simple stack example Stack is part of java.util.Collections hierarchy  It's an OO abomination, extends Vector (like ArrayList) Should be implemented using Vector Doesn't model "is-a" inheritance  what does pop do? What does push do? Stack s = new Stack(); s.push("panda"); s.push("grizzly"); s.push("brown"); System.out.println("size = "+s.size()); System.out.println(s.peek()); Object o = s.pop(); System.out.println(s.peek()); System.out.println(s.pop());

CPS Implementation is very simple l Extends Vector, so simply wraps Vector/ArrayList methods in better names  push==add, pop==remove  Note: code below for ArrayList, Vector is actually used. public Object push(Object o){ add(o); return o; } public Object pop(Object o){ return remove(size()-1); }

CPS Uses rather than "is-a" l Suppose there's a private ArrayList, myStorage  Doesn't extend Vector, simply uses Vector/ArrayList  Disadvantages of this approach? Synchronization issues public Object push(Object o){ myStorage.add(o); return o; } public Object pop(Object o){ return myStorage.remove(size()-1); }

CPS Postfix, prefix, and infix notation l Postfix notation used in some HP calculators  No parentheses needed, precedence rules still respected * *  Read expression For number/operand: push For operator: pop, pop, operate, push l See Postfix.java for example code, key ideas:  Use StringTokenizer, handy tool for parsing  Note: Exceptions thrown, what are these? l What about prefix and infix notations, advantages?

CPS Exceptions l Exceptions are raised or thrown in exceptional cases  Bad indexes, null pointers, illegal arguments, …  File not found, URL malformed, … l Runtime exceptions aren't meant to be handled or caught  Bad index in array, don't try to handle this in code  Null pointer stops your program, don't code that way! l Other exceptions must be caught or rethrown  See FileNotFoundException and IOException in Scanner class implementation l RuntimeException extends Exception, catch not required

CPS Prefix notation in action l Scheme/LISP and other functional languages tend to use a prefix notation (define (square x) (* x x)) (define (expt b n) (if (= n 0) 1 (* b (expt b (- n 1)))))

CPS Postfix notation in action l Practical example of use of stack abstraction l Put operator after operands in expression  Use stack to evaluate operand: push onto stack operator: pop operands push result l PostScript is a stack language mostly used for printing  drawing an X with two equivalent sets of code %! moveto rlineto moveto 100 –100 rlineto stroke showpage %! 100 – moveto rlineto stroke showpage

CPS Queue: another linear ADT l FIFO: first in, first out, used in many applications  Scheduling jobs/processes on a computer  Tenting policy?  Computer simulations l Common operations  Add to back, remove from front, peek at front No standard java.util.Queue, instead java.util.LinkedList addLast(), getFirst(), removeFirst, size() Can use add() rather than addLast(); l Downside of using LinkedList as queue  Can access middle elements, remove last, etc. why?

CPS Stack and Queue implementations l Different implementations of queue (and stack) aren’t really interesting from an algorithmic standpoint  Complexity is the same, performance may change (why?)  Use ArrayList, growable array, Vector, linked list, … Any sequential structure l As we'll see java.util.LinkedList is good basis for all  In Java 5, LinkedList implements the new Queue interface l ArrayList for queue is tricky, ring buffer implementation, add but wrap-around if possible before growing  Tricky to get right (exercise left to reader)

CPS Using linear data structures l We’ve studied arrays, stacks, queues, which to use?  It depends on the application  ArrayList is multipurpose, why not always use it? Make it clear to programmer what’s being done Other reasons? l Other linear ADTs exist  List: add-to-front, add-to-back, insert anywhere, iterate Alternative: create, head, tail, Lisp or Linked-list nodes are concrete implementation  Deque: add-to-front, add-to-back, random access Why is this “better” than an ArrayList? How to implement?

CPS Jaron LanierJaron Lanier ( Jaron Lanier is a computer scientist, composer, visual artist, and author. He coined the term ‘Virtual Reality’ … he co-developed the first implementations of virtual reality applications in surgical simulation, vehicle interior prototyping, virtual sets for television production, and assorted other areas "What's the difference between a bug and a variation or an imperfection? If you think about it, if you make a small change to a program, it can result in an enormous change in what the program does. If nature worked that way, the universe would crash all the time." Lanier has no academic degrees

CPS Stacks and Queues l How do we make queues in a stack-only land?  Can we do it with one stack?  2 stacks? l What are the operations necessary for a stack and a queue?

CPS Problem l Married couple hosts a party  Invites only other married couples  At least one person of an invited couple is acquainted to at least the host or the hostess  Upon arrival at the party, each person shakes hands with all other guests he/she doesn’t know l Hostess mingles and asks everyone including her husband, “How many hands did you shake?”  To her surprise, all responses are different l How many hands the the host and hostess each shake?

CPS How to solve? l Say there are 2n people at the party l What must have been the range of responses? l Make a ring of handshakers