Document Sample

Stacks Outline and Reading The Stack ADT (§4.1) Applications of Stacks Array-based implementation (§4.1.2) Growable array-based stack Think of a spring-loaded plate dispenser week 2a 2 Abstract Data Types (ADTs) An abstract data Example: ADT modeling a type (ADT) is an simple stock trading system abstraction of a The data stored are buy/sell data structure orders An ADT specifies: The operations supported are Data stored order buy(stock, shares, price) Operations on the order sell(stock, shares, price) data void cancel(order) Error conditions Error conditions: associated with Buy/sell a nonexistent stock operations Cancel a nonexistent order week 2a 3 The Stack ADT The Stack ADT stores Auxiliary stack arbitrary objects operations: Insertions and object top(): returns the last inserted element deletions follow the without removing it last-in first-out scheme integer size(): returns the Main stack operations: number of elements stored push(object): inserts an boolean isEmpty(): element indicates whether no object pop(): removes elements are stored and returns the last inserted element week 2a 4 Exceptions Attempting the In the Stack ADT, execution of an operations pop and operation of ADT may top cannot be sometimes cause an performed if the error condition, called stack is empty an exception Attempting the Exceptions are said to execution of pop or be “thrown” by an top on an empty operation that cannot stack throws an be executed EmptyStackException week 2a 5 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 Indirect applications Auxiliary data structure for algorithms Component of other data structures week 2a 6 Method Stack in the JVM The Java Virtual Machine (JVM) main() { keeps track of the chain of int i = 5; bar active methods with a stack foo(i); PC = 1 When a method is called, the } m=6 JVM pushes on the stack a foo(int j) { frame containing foo int k; PC = 3 Local variables and return value Program counter, keeping track of k = j+1; j=5 the statement being executed bar(k); k=6 When a method ends, its frame } is popped from the stack and main bar(int m) { PC = 2 control is passed to the method … i=5 on top of the stack } week 2a 7 Array-based Stack A simple way of Algorithm size() implementing the return t + 1 Stack ADT uses an array Algorithm pop() We add elements if isEmpty() then from left to right throw EmptyStackException A variable keeps else track of the index of tt1 the top element return S[t + 1] … S 0 1 2 t week 2a 8 Array-based Stack (cont.) The array storing the stack elements may Algorithm push(o) become full if t = S.length 1 then A push operation will throw FullStackException then throw a FullStackException else Limitation of the array- tt+1 based implementation S[t] o Not intrinsic to the Stack ADT … S 0 1 2 t week 2a 9 Performance and Limitations Performance Let n be the number of elements in the stack The space used is O(n) Each operation runs in time O(1) Limitations The maximum size of the stack must be defined a priori and cannot be changed Trying to push a new element into a full stack causes an implementation-specific exception week 2a 10 Computing Spans 7 We show how to use a stack 6 as an auxiliary data structure 5 in an algorithm 4 Given an an array X, the span S[i] of X[i] is the maximum 3 number of consecutive 2 elements X[j] immediately 1 preceding X[i] and such that 0 X[j] X[i] 0 1 2 3 4 Spans have applications to financial analysis X 6 3 4 5 2 E.g., stock at 52-week high S 1 1 2 3 1 week 2a 11 Quadratic Algorithm Algorithm spans1(X, n) Input array X of n integers Output array S of spans of X # S new array of n integers n for i 0 to n 1 do n s1 n while s i X[i s] X[i] 1 + 2 + …+ (n 1) ss+1 1 + 2 + …+ (n 1) S[i] s n return S 1 Algorithm spans1 runs in O(n2) time week 2a 12 Computing Spans with a Stack We keep in a stack the 7 indices of the elements 6 visible when “looking back” 5 4 We scan the array from left to right 3 Let i be the current index 2 We pop indices from the 1 stack until we find index j 0 such that X[i] X[j] 0 1 2 3 4 5 6 7 We set S[i] i j We push i onto the stack week 2a 13 Linear Algorithm Each index of the Algorithm spans2(X, n) # array S new array of n integers n Is pushed into the A new empty stack 1 stack exactly one for i 0 to n 1 do n Is popped from the stack at most while (A.isEmpty() once X[top()] X[i] ) do n The statements in A.pop() n the while-loop are if A.isEmpty() then n executed at most S[i] i + 1 n n times else S[i] i A.top() n Algorithm spans2 A.push(i) n runs in O(n) time return S 1 week 2a 14 Growable Array-based Stack In a push operation, when Algorithm push(o) the array is full, instead of if t = S.length 1 then throwing an exception, we A new array of can replace the array with size … a larger one for i 0 to t do How large should the new A[i] S[i] array be? SA incremental strategy: tt+1 increase the size by a S[t] o constant c doubling strategy: double the size week 2a 15 Comparison of the Strategies We compare the incremental strategy and the doubling strategy by analyzing the total time T(n) needed to perform a series of n push operations We assume that we start with an empty stack represented by an array of size 1 We call amortized time of a push operation the average time taken by a push over the series of operations, i.e., T(n)/n week 2a 16 Incremental Strategy Analysis We replace the array k = n/c times The total time T(n) of a series of n push operations is proportional to n + c + 2c + 3c + 4c + … + kc = n + c(1 + 2 + 3 + … + k) = n + ck(k + 1)/2 Since c is a constant, T(n) is O(n + k2), i.e., O(n2) The amortized time of a push operation is O(n) week 2a 17 Doubling Strategy Analysis We replace the array k = log2 n times geometric series The total time T(n) of a series of n push operations is 2 proportional to 4 n + 1 + 2 + 4 + 8 + …+ 2k = 1 1 n + 2k + 1 1 = 2n 1 8 T(n) is O(n) The amortized time of a push operation is O(1) week 2a 18 Stack Interface in Java public interface Stack { Java interface corresponding to public int size(); our Stack ADT public boolean isEmpty(); Requires the definition of class public Object top() throws EmptyStackException; EmptyStackException Different from the public void push(Object o); built-in Java class public Object pop() java.util.Stack throws EmptyStackException; } week 2a 19 Array-based Stack in Java public class ArrayStack public Object pop() implements Stack { throws EmptyStackException { // holds the stack elements if isEmpty() private Object S[ ]; throw new EmptyStackException (“Empty stack: cannot pop”); // index to top element Object temp = S[top]; private int top = -1; // facilitates garbage collection // constructor S[top] = null; public ArrayStack(int capacity) { top = top – 1; S = new Object[capacity]); return temp; } } week 2a 20 Queues Outline and Reading The Queue ADT (§4.2) Implementation with a circular array (§4.2.2) Growable array-based queue Queue interface in Java week 2a 22 The Queue ADT The Queue ADT stores arbitrary Auxiliary queue objects operations: Insertions and deletions follow object front(): returns the the first-in first-out scheme element at the front without Insertions are at the rear of the removing it queue and removals are at the integer size(): returns the front of the queue number of elements stored boolean isEmpty(): indicates Main queue operations: whether no elements are enqueue(object): inserts an stored element at the end of the queue Exceptions object dequeue(): removes and Attempting the execution of returns the element at the front dequeue or front on an of the queue empty queue throws an EmptyQueueException week 2a 23 Applications of Queues Direct applications Waiting lists, bureaucracy Access to shared resources (e.g., printer) Multiprogramming Indirect applications Auxiliary data structure for algorithms Component of other data structures week 2a 24 Array-based Queue Use an array of size N in a circular fashion Two variables keep track of the front and rear f index of the front element r index immediately past the rear element Array location r is kept empty normal configuration Q 0 1 2 f r wrapped-around configuration Q 0 1 2 r f week 2a 25 Queue Operations We use the Algorithm size() modulo operator return (N f + r) mod N (remainder of Algorithm isEmpty() division) return (f = r) Q 0 1 2 f r Q 0 1 2 r f week 2a 26 Queue Operations (cont.) Operation enqueue Algorithm enqueue(o) throws an exception if if size() = N 1 then the array is full throw FullQueueException This exception is else implementation- Q[r] o dependent r (r + 1) mod N Q 0 1 2 f r Q 0 1 2 f r week 2a 27 Queue Operations (cont.) Operation dequeue Algorithm dequeue() throws an exception if isEmpty() then if the queue is empty throw EmptyQueueException This exception is else specified in the o Q[f] queue ADT f (f + 1) mod N return o Q 0 1 2 f r Q 0 1 2 f r week 2a 28 Growable Array-based Queue In an enqueue operation, when the array is full, instead of throwing an exception, we can replace the array with a larger one Similar to what we did for an array-based stack The enqueue operation has amortized running time O(n) with the incremental strategy O(1) with the doubling strategy week 2a 29 Queue Interface in Java public interface Queue { Java interface corresponding to public int size(); our Queue ADT public boolean isEmpty(); Requires the public Object front() definition of class throws EmptyQueueException; EmptyQueueException public void enqueue(Object o); No corresponding public Object dequeue() built-in Java class throws EmptyQueueException; } week 2a 30 Creativity: Describe in pseudo-code a linear-time algorithm for reversing a queue Q. To access the queue, you are only allowed to use the methods of queue ADT. week 2a 31 Answer: Algorithm reverseQueue(Queue Q) Create new stack S while (not Q.isEmpty()) do S.push(Q.dequeue()) while (not S.isEmpty()) do Q.enqueue(S.pop()) week 2a 32

DOCUMENT INFO

Shared By:

Categories:

Tags:
Condenser Microphone, Samson Audio, phantom power, Office Furniture, shipping costs, Stack Chair, file type, Live Spaces, high-pass filter, Samson C01

Stats:

views: | 17 |

posted: | 6/9/2010 |

language: | English |

pages: | 32 |

OTHER DOCS BY niusheng11

How are you planning on using Docstoc?
BUSINESS
PERSONAL

By registering with docstoc.com you agree to our
privacy policy and
terms of service, and to receive content and offer notifications.

Docstoc is the premier online destination to start and grow small businesses. It hosts the best quality and widest selection of professional documents (over 20 million) and resources including expert videos, articles and productivity tools to make every small business better.

Search or Browse for any specific document or resource you need for your business. Or explore our curated resources for Starting a Business, Growing a Business or for Professional Development.

Feel free to Contact Us with any questions you might have.