CIS 121 Data Structures and Algorithms with Java Spring Stacks and Queues Monday, February 12 / Tuesday, February 13

Similar documents
CIS 121 Data Structures and Algorithms with Java Spring Stacks, Queues, and Heaps Monday, February 18 / Tuesday, February 19

Heaps. Presentation for use with the textbook Algorithm Design and Applications, by M. T. Goodrich and R. Tamassia, Wiley, 2015

DATA STRUCTURES. amortized analysis binomial heaps Fibonacci heaps union-find. Data structures. Appetizer. Appetizer

Computer Science Foundation Exam. August 12, Computer Science. Section 1A. No Calculators! KEY. Solutions and Grading Criteria.

Algorithm Design Techniques. Divide and conquer Problem

CIS 121. Introduction to Trees

6.854J / J Advanced Algorithms Fall 2008

Solution printed. Do not start the test until instructed to do so! CS 2604 Data Structures Midterm Spring, Instructions:

top() Applications of Stacks

Homework 1 Solutions MA 522 Fall 2017

Examples and Applications of Binary Search

CSC165H1 Worksheet: Tutorial 8 Algorithm analysis (SOLUTIONS)

University of Waterloo Department of Electrical and Computer Engineering ECE 250 Algorithms and Data Structures

Data Structures Week #5. Trees (Ağaçlar)

Graphs. Minimum Spanning Trees. Slides by Rose Hoberman (CMU)

CIS 121 Data Structures and Algorithms with Java Fall Big-Oh Notation Tuesday, September 5 (Make-up Friday, September 8)

why study sorting? Sorting is a classic subject in computer science. There are three reasons for studying sorting algorithms.

Minimum Spanning Trees

BST Sequence of Operations

. Written in factored form it is easy to see that the roots are 2, 2, i,

Chapter 24. Sorting. Objectives. 1. To study and analyze time efficiency of various sorting algorithms

Lecture 5. Counting Sort / Radix Sort

COSC 1P03. Ch 7 Recursion. Introduction to Data Structures 8.1

Sorting 9/15/2009. Sorting Problem. Insertion Sort: Soundness. Insertion Sort. Insertion Sort: Running Time. Insertion Sort: Soundness

Fundamental Algorithms

Major CSL Write your name and entry no on every sheet of the answer script. Time 2 Hrs Max Marks 70

End Semester Examination CSE, III Yr. (I Sem), 30002: Computer Organization

Recursion. Recursion. Mathematical induction: example. Recursion. The sum of the first n odd numbers is n 2 : Informal proof: Principle:

5.3 Recursive definitions and structural induction

Chapter 9. Pointers and Dynamic Arrays. Copyright 2015 Pearson Education, Ltd.. All rights reserved.

Lecture 1: Introduction and Strassen s Algorithm

Lecture 6. Lecturer: Ronitt Rubinfeld Scribes: Chen Ziv, Eliav Buchnik, Ophir Arie, Jonathan Gradstein

n n B. How many subsets of C are there of cardinality n. We are selecting elements for such a

Data Structures and Algorithms Part 1.4

The isoperimetric problem on the hypercube

Sorting in Linear Time. Data Structures and Algorithms Andrei Bulatov

15-859E: Advanced Algorithms CMU, Spring 2015 Lecture #2: Randomized MST and MST Verification January 14, 2015

CMPT 125 Assignment 2 Solutions

Priority Queues. Binary Heaps

Analysis of Algorithms

quality/quantity peak time/ratio

Lecturers: Sanjam Garg and Prasad Raghavendra Feb 21, Midterm 1 Solutions

Basic allocator mechanisms The course that gives CMU its Zip! Memory Management II: Dynamic Storage Allocation Mar 6, 2000.

Morgan Kaufmann Publishers 26 February, COMPUTER ORGANIZATION AND DESIGN The Hardware/Software Interface. Chapter 5

Random Graphs and Complex Networks T

CSE 2320 Notes 8: Sorting. (Last updated 10/3/18 7:16 PM) Idea: Take an unsorted (sub)array and partition into two subarrays such that.

Combination Labelings Of Graphs

Running Time. Analysis of Algorithms. Experimental Studies. Limitations of Experiments

Lecture Notes 6 Introduction to algorithm analysis CSS 501 Data Structures and Object-Oriented Programming

Big-O Analysis. Asymptotics

Pseudocode ( 1.1) Analysis of Algorithms. Primitive Operations. Pseudocode Details. Running Time ( 1.1) Estimating performance

Minimum Spanning Trees

Running Time ( 3.1) Analysis of Algorithms. Experimental Studies. Limitations of Experiments

Analysis of Algorithms

Minimum Spanning Trees. Application: Connecting a Network

Ones Assignment Method for Solving Traveling Salesman Problem

Massachusetts Institute of Technology Lecture : Theory of Parallel Systems Feb. 25, Lecture 6: List contraction, tree contraction, and

Lecture 5: Recursion. Recursion Overview. Recursion is a powerful technique for specifying funclons, sets, and programs

Linked Lists 11/16/18. Preliminaries. Java References. Objects and references. Self references. Linking self-referential nodes

How do we evaluate algorithms?

WORKED EXAMPLE 7.1. Producing a Mass Mailing. We want to automate the process of producing mass mailings. A typical letter might look as follows:

n Some thoughts on software development n The idea of a calculator n Using a grammar n Expression evaluation n Program organization n Analysis

IMP: Superposer Integrated Morphometrics Package Superposition Tool

Hash Tables. Presentation for use with the textbook Algorithm Design and Applications, by M. T. Goodrich and R. Tamassia, Wiley, 2015.

3. b. Present a combinatorial argument that for all positive integers n : : 2 n

Computational Geometry

2. ALGORITHM ANALYSIS

Review: The ACID properties

Abstract. Chapter 4 Computation. Overview 8/13/18. Bjarne Stroustrup Note:

NTH, GEOMETRIC, AND TELESCOPING TEST

Outline and Reading. Analysis of Algorithms. Running Time. Experimental Studies. Limitations of Experiments. Theoretical Analysis

Design and Analysis of Algorithms Notes

CSE 417: Algorithms and Computational Complexity

CS200: Hash Tables. Prichard Ch CS200 - Hash Tables 1

Analysis Metrics. Intro to Algorithm Analysis. Slides. 12. Alg Analysis. 12. Alg Analysis

The Magma Database file formats

Our Learning Problem, Again

Chapter 8. Strings and Vectors. Copyright 2014 Pearson Addison-Wesley. All rights reserved.

Lower Bounds for Sorting

Data Structures and Algorithms. Analysis of Algorithms

Threads and Concurrency in Java: Part 1

Chapter 8. Strings and Vectors. Copyright 2015 Pearson Education, Ltd.. All rights reserved.

Big-O Analysis. Asymptotics

Threads and Concurrency in Java: Part 1

Data Structures Week #9. Sorting

Our second algorithm. Comp 135 Machine Learning Computer Science Tufts University. Decision Trees. Decision Trees. Decision Trees.

Chapter 3 Classification of FFT Processor Algorithms

CS211 Fall 2003 Prelim 2 Solutions and Grading Guide

EE123 Digital Signal Processing

Greedy Algorithms. Interval Scheduling. Greedy Algorithms. Interval scheduling. Greedy Algorithms. Interval Scheduling

Algorithm. Counting Sort Analysis of Algorithms

Python Programming: An Introduction to Computer Science

What are we going to learn? CSC Data Structures Analysis of Algorithms. Overview. Algorithm, and Inputs

Python Programming: An Introduction to Computer Science

Elementary Educational Computer

Pattern Recognition Systems Lab 1 Least Mean Squares

EVALUATION OF TRIGONOMETRIC FUNCTIONS

Thompson s Group F (p + 1) is not Minimally Almost Convex

CS 111: Program Design I Lecture # 7: First Loop, Web Crawler, Functions

Classes and Objects. Again: Distance between points within the first quadrant. José Valente de Oliveira 4-1

Transcription:

CIS Data Structures ad Algorithms with Java Sprig 08 Stacks ad Queues Moday, February / Tuesday, February Learig Goals Durig this lab, you will: Review stacks ad queues. Lear amortized ruig time aalysis ad stregthe ituitio for applyig it to ew problems. Practice usig stacks ad queues to accomplish a variety of tasks. Stacks ad Queues Recall the stack ad queue ADTs (abstract data types from lecture. Each is characterized by a specific way of removig elemets ad has a set of supported operatios. Stack Queue LIFO (last-i-first-out the most recet elemet that has bee added to the stack will be removed first. Supported operatios: push pop peek isempty size FIFO (first-i-first-out the least recet elemet that has bee added to the queue will be removed first. Supported operatios: equeue dequeue peek isempty size Implemetatio Details Stacks ad queues ca be implemeted uder the hood with almost ay data structure. I this course, we will implemet stacks ad queues usig expadable arrays. The rules we will use for icreasig or decreasig the size of a stack or queue s uderlyig array are as follows:. If the array of size is full, create a ew array of size, ad copy all elemets ito the ew array.. If the array of size has elemets i it, create a ew array of size, ad copy all elemets ito the ew array. Problems Problem : Sortig Usig Stacks Give: A full stack S of size ad a empty stack S of size. Objective: Sort the elemets i ascedig order i S. You may oly use the give stacks S ad S (each of size ad O( additioal space. What is the ruig time of your sortig procedure? Example:

Hit: Start with a simpler example: Solutio To solve this problem, we will use the two give stacks, S ad S, ad two extra variables max ad size. Algorithm: Iitialize max to ad size to 0.. pop all elemets from S ad push them oto S. While pop ig, keep track of the maximum elemet we have see so far i max. Oce we have push ed all elemets ito S, the absolute maximum elemet will be stored i max.. pop all elemets from S ad push all except the maximum elemet max back ito S.. push the maximum elemet (stored i max ito S. Now S cotais usorted elemets, ad S cotais sorted elemet.. Icremet size by. We will use size to keep track of the umber of sorted elemets i S so that we do t pop them.. Repeat steps - util size =. I Step, take care to oly pop elemets from S util S cotais exactly size elemets. (The bottom size elemets i S have already bee sorted. Whe the procedure termiates, S will be empty, ad S cotais the elemets i o-decreasig order. Time complexity: The ruig time of our sortig procedure is O(, sice for each elemet that we sort, we must push ad pop at most elemets. Problem : Level-Order traversal of Biary Tree Give: A biary tree of size Objective: Prit out the level order traversal of the biary tree Example: see below Figure : For this tree, your fuctio should prit,,, 7, 6,,.

Solutio Algorithm: We use a queue to hold odes that are to be visited. We first start with the queue cotaiig the root ode of the tree. While the queue is ot empty, we dequeue a elemet from the queue, mark it as visited, ad the equeue its childre ito the queue. for the tree above, we first start with ode i the queue. We remove, mark it as visited, ad add, to the queue. We the remove ad 7, 6 to the queue. We remove ad add, to the queue. Sice all odes i the queue at this poit are leaves, we remove each ode oe by oe util the queue is empty. Problem : Spiral Order Tree Traversal Give: A biary tree T. Objective: Prit the spiral order traversal of the tree T. Example: Hit: Try usig stacks. Solutio Figure : For this tree, your fuctio should prit,,,,, 6, 7. We will use two stacks, S ad S. We will use S to hold elemets i the same level that are beig prited from left to right, ad we will use S to hold elemets i the same level that are beig prited from right to left. We observe that these stacks are disjoit (i.e., they cotai o overlappig elemets, ad if a give ode i T is i S, the its two childre should be i S (ad vice versa. Algorithm: First, push the root of the tree T oto stack S. The followig procedure will loop util both S ad S are empty. While S is ot empty, pop the top elemet from S. Prit. If has a right child, push it oto the other stack S. The, if has a left child, push it oto S. Cotiue this step util S is empty. While S is ot empty, pop the top elemet from S. Prit. If has a left child, push it oto the other stack S. The, if has a right child, push it oto S. Cotiue this step util S is empty. Time ad space complexity: If the tree T cotais odes, this solutio takes O( time ad O( extra space.

Amortized Aalysis Amortized aalysis refers to fidig the time-averaged cost for a sequece of operatios. I other words, it is the time required to perform a sequece of operatios averaged over all the operatios performed. Sice amortized aalysis for the stack push operatio was covered i lecture, we are goig to take a closer look at the stack pop operatio. The worst case ruig time for a sigle pop operatio is O(, sice we may eed to resize the array ad copy the elemets ito it. Based o this ruig time, we might coclude that a tight boud for the worst case ruig time for pop operatios is O(, sice there are operatios ad each operatio takes worst case O( time; however, we ca fid a tighter boud through some careful aalysis. If we start from a full stack of size, what is the total cost of a sequece of pop operatios? Iitially, the array is of size ad cotais elemets. To make our aalysis simpler, let s immediately pop the first elemets. Each of these pops takes O( time. Now our array is of size but cotais oly elemets. I accordace with our rules, we ca pop more elemets before resizig the array. Each of these pops takes O( time. Oce we have pop d those elemets (leavig us with elemets i our array, we must reduce the size of our array to, ad copy the remaiig elemets ito the ew array. Thus, the total cost for the first pop operatios is T ( = + + +. We ca apply idetical aalysis to the ew array of size that cotais elemets. We get ( = ( 8 pops for free, after which we resize the array to be of size = ad copy the remaiig ( = 8 elemets ( ito the smaller array. Thus, the total cost for the first 7 8 pop operatios is T ( 7 8 = + + + + 8 + + 8. Are you oticig a patter? Let s rewrite the expressio slightly ad cotiue to expad it: T ( = + ( 0 + 0 + ( 0 + + ( + We ca ow calculate the total cost of pop operatios: T ( + i=0 = + = + = O( i=0 + + + + + + ( i + i + i i ( ( + ( + ( (The first term i the summatio is the cost of the iitial pops, the secod term is the cost of allocatig a ew array, ad the third term is the cost of copyig the remaiig elemets ito the ew array. Thus, the amortized time complexity of a pop operatio is = O(, eve though the worst case time complexity of a sigle pop operatio is O(. Problem : Queue With Two Stacks Give: Two stacks S ad S, each of size. Objective: Implemet a queue usig S ad S. Your queue s equeue ad dequeue methods should be implemeted usig oly your stacks push, pop, ad/or peek methods. What are the ruig times of your ew queue s equeue ad dequeue methods?

Solutio equeue(x:. push x ito S. dequeue:. If S is empty, pop all elemets from S ad push them ito S.. If S is still empty, retur Nil.. Else pop a elemet from S ad retur it. Time complexity: The ruig time of equeue(x is clearly O(. The ruig time for dequeue is a bit trickier. If we cosider that each elemet will be i each Stack exactly oce, the we realize that each elemet will be pushed exactly twice ad popped exactly twice. Thus, the amortized ruig time of dequeue is O(.