Recurrences v Summing Numbers int sumint n if
Recurrences v Summing Numbers int sum(int n) { if (0 == n) return 0; else return n + sum(n-1); } v v What is complexity? justification? T(n) = time to compute sum for n T(n) = T(n-1) + 1 T(0) = 1 v instead of 1, use O(1) for constant time q Comp. Sci 100 independent of n, the measure of problem size 6. 1
Solving recurrence relations v Plug, simplify, reduce, guess, verify? T(n) = T(n-1) + 1 T(0) = 1 T(n-1) = T(n-1 -1) + 1 = T(n-2) + 1 T(n) = [T(n-2) + 1] + 1 = T(n-2)+2 T(n-2) = T(n-2 -1) + 1 = T(n-3) + 1 T(n) = [(T(n-3) + 1] + 1 = T(n-3)+3 T(n) = T(n-k) + k find the pattern! Want n-k = 0, or k=n, then T(n) = T(0)+n = 1 + n v Get to base case, solve the recurrence: O(n) Comp. Sci 100 6. 2
Complexity Practice v What is complexity of Build? (what does it do? ) Array. List build(int n) { if (0 == n) return new Array. List(); // empty Array. List list = build(n-1); for(int k=0; k < n; k++){ list. add(new Integer(n)); } return list; } v v v Have seen this earlier Write an expression for T(n) and for T(0) Solve Comp. Sci 100 6. 3
Recognizing Recurrences v Solve once, re-use in new contexts q q T(n) T(n) v T must be explicitly identified n must be some measure of size of input/parameter o T(n) is the time for quicksort to run on an n-element vector = = = T(n/2) T(n-1) 2 T(n/2) T(n-1) + + + O(1) O(n) binary search sequential search tree traversal quicksort selection sort O( log n ) O( ) n O( n log n) O( n 2 ) Remember the algorithm, re-derive complexity Comp. Sci 100 6. 4
Stack: What problems does it solve? v Stacks are used to avoid recursion, a stack can replace the implicit/actual stack of functions called recursively v Stacks are used to evaluate arithmetic expressions, to implement compilers, to implement interpreters q q q v 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 Small set of operations: LIFO or last in is first out access q q Comp. Sci 100 Operations: push, pop, top, create, clear, size More in postscript, e. g. , swap, dup, rotate, … 6. 5
Simple stack example v Stack is part of java. util. Collections hierarchy q q It's an OO abomination, extends Vector (like Array. List) o Should be implemented using Vector o 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()); Comp. Sci 100 6. 6
Implementation is very simple v Extends Vector, so simply wraps Vector/Array. List methods in better names q q push==add, pop==remove Note: code below for Array. List, Vector is actually used. public Object push(Object o){ add(o); return o; } public Object pop(Object o){ return remove(size()-1); } Comp. Sci 100 6. 7
Uses rather than "is-a" v Suppose there's a private Array. List, my. Storage q q Doesn't extend Vector, simply uses Vector/Array. List Disadvantages of this approach? o Synchronization issues public Object push(Object o){ my. Storage. add(o); return o; } public Object pop(Object o){ return my. Storage. remove(size()-1); } Comp. Sci 100 6. 8
Postfix, prefix, and infix notation v Postfix notation used in some HP calculators No parentheses needed, precedence rules still respected 3 5 + 4 2 * 7 + 3 2 9 7 + * q q v See Postfix. java for example code, key ideas: q q v Read expression o For number/operand: push o For operator: pop, operate, push Use String. Tokenizer, handy tool for parsing Note: Exceptions thrown, what are these? What about prefix and infix notations, advantages? Comp. Sci 100 6. 9
Exceptions v Exceptions are raised or thrown in exceptional cases q q v Runtime exceptions aren't meant to be handled or caught q q v Bad index in array, don't try to handle this in code Null pointer stops your program, don't code that way! Other exceptions must be caught or rethrown q v Bad indexes, null pointers, illegal arguments, … File not found, URL malformed, … See File. Not. Found. Exception and IOException in Scanner class implementation Runtime. Exception extends Exception, catch not required Comp. Sci 100 6. 10
Postfix notation in action v v Practical example of use of stack abstraction Put operator after operands in expression q v Use stack to evaluate o operand: push onto stack o operator: pop operands push result Post. Script is a stack language mostly used for printing q drawing an X with two equivalent sets of code %! 200 moveto 100 rlineto 200 300 moveto 100 – 100 rlineto stroke showpage Comp. Sci 100 %! 100 – 100 200 300 100 200 moveto rlineto stroke showpage 6. 11
Queue: another linear ADT v FIFO: first in, first out, used in many applications q q q v Scheduling jobs/processes on a computer Tenting policy? Computer simulations Common operations q Add to back, remove from front, peek at front o Queue interface added in 5. 0 o element(), offer(), peek(), poll(), remove() o Implemented by java. util. Linked. List o add. Last(), get. First(), remove. First, size() o Can use add() rather than add. Last(); v Downside of using Linked. List as queue q Comp. Sci 100 Can access middle elements, remove last, etc. why? 6. 12
Stack and Queue implementations v Different implementations of queue (and stack) aren’t really interesting from an algorithmic standpoint q q v As we'll see java. util. Linked. List is good basis for all q v Complexity is the same, performance may change (why? ) Use Array. List, growable array, Vector, linked list, … o Any sequential structure In Java 5, Linked. List implements the new Queue interface Array. List for queue is tricky, ring buffer implementation, add but wrap-around if possible before growing q Comp. Sci 100 Tricky to get right (exercise left to reader) 6. 13
Using linear data structures v We’ve studied arrays, stacks, queues, which to use? q q v It depends on the application Array. List is multipurpose, why not always use it? o Make it clear to programmer what’s being done o Other reasons? Other linear ADTs exist q q Comp. Sci 100 List: add-to-front, add-to-back, insert anywhere, iterate o Alternative: create, head, tail, Lisp or o Linked-list nodes are concrete implementation Deque: add-to-front, add-to-back, random access o Why is this “better” than an Array. List? o How to implement? 6. 14
- Slides: 14