Introduction to Algorithm Analysis Concepts 15-211 Fundamental Data Structures and Algorithms Peter Lee January 21, 2003.

Slides:



Advertisements
Similar presentations
Practicum 2: - Asymptotics - List and Tree Structures Fundamental Data Structures and Algorithms Klaus Sutner Feb. 5, 2004.
Advertisements

Analysis of Algorithms
Data Structures and Algorithms (60-254)
Stacks, Queues, and Deques. 2 A stack is a last in, first out (LIFO) data structure Items are removed from a stack in the reverse order from the way they.
Today’s Agenda  Stacks  Queues  Priority Queues CS2336: Computer Science II.
CSE332: Data Abstractions Lecture 21: Amortized Analysis Dan Grossman Spring 2010.
CS 106 Introduction to Computer Science I 12 / 06 / 2006 Instructor: Michael Eckmann.
Complexity Analysis (Part I)
CSE 326: Data Structures Lecture #3 Analysis of Recursive Algorithms Alon Halevy Fall Quarter 2000.
CS 106 Introduction to Computer Science I 12 / 11 / 2006 Instructor: Michael Eckmann.
1 CSE 326: Data Structures Program Analysis Lecture 3: Friday, Jan 8, 2003.
© 2006 Pearson Addison-Wesley. All rights reserved6-1 More on Recursion.
Algorithm Analysis CS 201 Fundamental Structures of Computer Science.
Analysis of Algorithms 7/2/2015CS202 - Fundamentals of Computer Science II1.
CS 106 Introduction to Computer Science I 12 / 13 / 2006 Instructor: Michael Eckmann.
Stacks, Queues, and Deques
Stacks, Queues, and Deques. A stack is a last in, first out (LIFO) data structure –Items are removed from a stack in the reverse order from the way they.
Chapter 1 Introduction Definition of Algorithm An algorithm is a finite sequence of precise instructions for performing a computation or for solving.
analysis, plug ‘n’ chug, & induction
Stacks, Queues, and Deques
EXPANDING STACKS AND QUEUES CS16: Introduction to Data Structures & Algorithms 1 Tuesday, February 10, 2015.
Analysis of Algorithms Spring 2015CS202 - Fundamentals of Computer Science II1.
Analysis of Algorithms Dilemma: you have two (or more) methods to solve problem, how to choose the BEST? One approach: implement each algorithm in C, test.
CSE332: Data Abstractions Lecture 26: Amortized Analysis Tyler Robison Summer
Abstract Data Types (ADTs) Data Structures The Java Collections API
CHAPTER 05 Compiled by: Dr. Mohammad Omar Alhawarat Stacks & Queues.
1 Chapter 24 Developing Efficient Algorithms. 2 Executing Time Suppose two algorithms perform the same task such as search (linear search vs. binary search)
{ CS203 Lecture 7 John Hurley Cal State LA. 2 Execution Time Suppose two algorithms perform the same task such as search (linear search vs. binary search)
CS 3343: Analysis of Algorithms
Chapters 7, 8, & 9 Quiz 3 Review 1. 2 Algorithms Algorithm A set of unambiguous instructions for solving a problem or subproblem in a finite amount of.
Nirmalya Roy School of Electrical Engineering and Computer Science Washington State University Cpt S 223 – Advanced Data Structures Course Review Midterm.
Computer Science Department Data Structure & Algorithms Lecture 8 Recursion.
Fundamentals CSE 373 Data Structures Lecture 5. 12/26/03Fundamentals - Lecture 52 Mathematical Background Today, we will review: ›Logs and exponents ›Series.
Week 12 - Wednesday.  What did we talk about last time?  Asymptotic notation.
1 Chapter 7 Stacks and Queues. 2 Stack ADT Recall that ADT is abstract data type, a set of data and a set of operations that act upon the data. In a stack,
Getting Started Introduction to Algorithms Jeff Chastine.
Algorithm Analysis CS 400/600 – Data Structures. Algorithm Analysis2 Abstract Data Types Abstract Data Type (ADT): a definition for a data type solely.
1 Linked-list, stack and queue. 2 Outline Abstract Data Type (ADT)‏ Linked list Stack Queue.
Advanced Algorithm Design and Analysis (Lecture 12) SW5 fall 2004 Simonas Šaltenis E1-215b
CSE373: Data Structures and Algorithms Lecture 3: Math Review; Algorithm Analysis Nicki Dell Spring 2014.
Data Structures and Algorithm Analysis Introduction Lecturer: Ligang Dong, egan Tel: , Office: SIEE Building.
+ David Kauchak cs312 Review. + Midterm Will be posted online this afternoon You will have 2 hours to take it watch your time! if you get stuck on a problem,
Week 5 - Wednesday.  What did we talk about last time?  Recursion  Definitions: base case, recursive case  Recursive methods in Java.
Week 2 - Friday.  What did we talk about last time?  Computing Big Oh.
Data Structures. Abstract Data Type A collection of related data is known as an abstract data type (ADT) Data Structure = ADT + Collection of functions.
Sorting Fundamental Data Structures and Algorithms Aleks Nanevski February 17, 2004.
Introduction to Algorithm Analysis Concepts Fundamental Data Structures and Algorithms Aleks Nanevski and Margaret Reid-Miller January 15, 2003.
CSE373: Data Structures & Algorithms Lecture 8: Amortized Analysis Dan Grossman Fall 2013.
Practicum 1: - Persistent vs. destructive lists - Java interfaces Fundamental Data Structures and Algorithms Margaret Reid-Miller January 22, 2004.
3/3/20161 Stacks and Queues Introduction to Data Structures Ananda Gunawardena.
Lecture 2 What is a computational problem? What is an instance of a problem? What is an algorithm? How to guarantee that an algorithm is correct? What.
Analysis of Algorithms Spring 2016CS202 - Fundamentals of Computer Science II1.
Chapter 15 Running Time Analysis. Topics Orders of Magnitude and Big-Oh Notation Running Time Analysis of Algorithms –Counting Statements –Evaluating.
CSE373: Data Structures and Algorithms Lecture 3: Math Review; Algorithm Analysis Linda Shapiro Winter 2015.
List Structures What is a list? A homogeneous collection of elements with a linear relationship between the elements linear relationship - each element.
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.
CMSC201 Computer Science I for Majors Lecture 19 – Recursion
Week 4 - Friday CS221.
Practicum 1: - Persistent vs. destructive lists - Java interfaces
CSE373: Data Structures and Algorithms Lecture 3: Math Review; Algorithm Analysis Catie Baker Spring 2015.
CS 3343: Analysis of Algorithms
CMSC201 Computer Science I for Majors Lecture 18 – Recursion
David Kauchak CS52 – Spring 2015
CMSC 341 Lecture 5 Stacks, Queues
Lesson Objectives Aims
CMSC201 Computer Science I for Majors Lecture 19 – Recursion
CSE 373: Data Structures & Algorithms
Mathematical Background 2
Algorithms: the big picture
Stacks, Queues, and Deques
Presentation transcript:

Introduction to Algorithm Analysis Concepts Fundamental Data Structures and Algorithms Peter Lee January 21, 2003

Plan  Today  Introduction to some basic concepts in the analysis of algorithms  Reading:  For today: Chapter 5 and  For next time: Chapter 18 and 19

Homework 1 is available!  See the Blackboard Assignments area  Due on Monday, Jan.27, 11:59pm  Get started today!

Induction  Recall proofs by induction:  If trying to prove that a property P(n) holds for all natural numbers 0, 1, 2, …, then  Prove the base case of P(0).  Assume P(n), show that P(n+1) holds.

Inductive definitions  A great deal of computer science can be defined inductively.  For example, we can think of the factorial function defined as follows:  fact(0) = 1  fact(n) = n * fact(n-1), for n>0

Inductive definition of lists  From last time, we also saw that induction can be used to define some data structures:  An integer list is either  empty, or  an integer paired with an integer list Base case Inductive case

Last week’s implementation public interface IntListInterface {…} public class IntList implements IntListInterface { public IntListInterface append(int n) { next = next.append(n); return this; } } public class EmptyList implements IntListInterface { public IntListInterface append(int n) { return new IntList(n); } }

Which … … prompts another question: What's the running time? Not “wall-clock” time, but the number of “steps”? Answer: The append is handed down to the end of the list, where it eventually causes a miraculous transformation. This could be as many as n “steps”, where n is the length of the list. A bit later, we will make some mathematical definitions to allow us to say that this is O(n), or linear time.

Our goal  Our goal is to compare algorithms against each other  Not compute the “wall-clock” time  We will also want to know if an algorithm is “fast”, “slow”, or maybe so slow as to be impractical

Input size  Generally, we care about this most when the amount of time required increases as the size or amount of input increases

The “step”  In order to abstract from a particular piece of hardware, operating system, and language, we will focus on counting the number of steps of an algorithm  A “step” should execute in constant time  That is, it’s execution time should not vary much when the size of the input varies

Why do we care about “steps”? n 100n sec7n 2 sec2 n sec s7 s2 s 5.5 ms 175 s32 s 101 ms.7 ms1 ms ms14 ms1 year ms7 sec10 16 year 1,0001 sec12 min-- 10,00010 sec20 hr-- 1,000, min.22 year--

Counting steps can be hard to do  Programs loop and make recursive calls  And their execution is dependent on (unknown) inputs  We’ll need to use math to help us!

List reversal public class IntList implements IntListInterface { public IntListInterface reverse() { IntListInterface t = next.reverse(); if (t == null) return this; return t.append(element); } public class EmptyList implements IntListInterface { public IntListInterface reverse() { return this; } }

Example: list reversal  The reversal of a list L is:  L, if L is empty  M.append(n), otherwise  where n is the first element of L, and  M is the reversal of the tail of L

Example: list reversal  The reversal of a list L is:  L, if L is empty  M.append(n), otherwise  where n is the first element of L, and  M is the reversal of the tail of L some constant- time steps

First Running Time For EmptyList clearly just one “step”. This is called constant time, or O(1) For IntList: - the #steps for the tail, plus - the #steps for append Ignoring constants: t(0) = 1 t(n) = n + t(n-1) Solving for t would tell us how many “steps” it takes to reverse a list

Klaus said that this is easy… t(n) = n + (n-1) + (n-2) + … 1 = n(n-1)/2 But how on earth did he come up with this beautiful little closed-form solution?

Solving recurrence equations  Klaus has already shown us one very common first step:  repeated substitution  t(n) = n + t(n-1)  = n + (n-1) + t(n-2)  = n + (n-1) + (n-2) + t(n-3)  and so on…  = n + (n-1) + (n-2) + (n-3) + … + 1

Incrementing series  By the way, this is an arithmetic seires that comes up over and over again, because characterizes many nested loops: for (i=1; i<n; i++) { for (j=1; j<i; j++) { f(); }

Mathematical handbooks  For really common series like this one, standard textbooks and mathematical handbooks will usually provide closed-form solutions.  So, one way is simply to look up the answer.  Another way is to try to think visually…

Visualizing it n n 0123… … Area: n 2 /2 Area of the leftovers: n/2 So: n 2 /2 + n/2 = (n 2 +n)/2 = n(n+1)/2

Proving it  Yet another approach is to start with an answer or a guess, and then verify it by induction.  t(1) = 1(1+1)/2 = 1  Inductive case:  for n>1, assume t(n-1) = (n-1)(n-1+1)/2 = (n-1) 2 /2 = n 2 /2 – n + 1/2  then t(n) = n + n 2 /2 – n + 1/2  = n 2 /2 + 1/2  = n(n+1)/2

Summations  Arithmetic and geometric series come up everywhere in analysis of algorithms.  Some series come up so frequently that every computer scientist should know them by heart.

How to Sort a List? Sorting an array is easy and we know many algorithms. But how do we sort a singly linked list? As always, think inductively: sort(nil) = nil sort(L) = insert head(L) in “order” to sort(tail(L))

Insertion sort

Code for ordered insert public IntList(int x, IntList head) { num = x; next = head; } public IntList order_insert(int x) { if( x <= num ) return new IntList(x,this); next = next.order_insert(x); return this; } tail takes care of placement new constructor method

Analysis of ordered insert This creates only one new object (the node holding x). The running time depends on the position of x in the new list. But in the worst case this could take n steps.

Analysis of sort() sort(nil) = nil sort(L) = insert the head into the right place in sort(tail(L)) t(0) = 1 t(n) = n + t(n-1) and we already know the answer to this…

Insertion sort for i = 2 to n do insert a[i] in the proper place in a[1:i-1] This is yet another example of a doubly- nested loop…

How fast is insertion sort? We’ve essentially counted the number of computation steps in the worst case. But what happens if the elements are nearly sorted to begin with?

Worst-case analysis  We’ll have much more to say, later in the course, about “worst-case” vs “average-case” vs “expected case” performance.

How long does it take to sort?  Can we do better than n(n+1)/2?  In the worst case?  In the average case?  We’ll find out later…

Quiz Break

Doubling summation Like the incrementing summation, sums of powers of 2 are also encountered frequently in computer science. What is the closed-form solution for this sum? Prove your answer by induction.

Hint 1: Visualizing it Imagine filling a glass by halves… 2 n-1 2 n-2 2 n-3 2 n-4 2 n-5

Hint 2: Visualizing it  A somewhat geekier hint: term in binary … What is the sum of this column of binary numbers?

Proving it  Base case:  When n=1, then 2 0 =  Induction step, when n>1.  Assume true for n’<n, consider n  By the IH, then

Stacks and Queues, Revisited

A Stack interface public interface Stack { public void push(Object x); public void pop(); public Object top(); public boolean isEmpty(); public void makeEmpty(); }

Stacks are LIFO a b c d e Push operations:

Stacks are LIFO a b c d e Pop operation: Last element that was pushed is the first to be popped.

A Queue interface public interface Queue { public void enqueue(Object x); public Object dequeue(); public boolean isEmpty(); public void makeEmpty(); }

Queues are FIFO front back krqcm

Queues are FIFO front back krqcm y Enqueue operation:

Queues are FIFO frontback krqcmy Enqueue operation:

Queues are FIFO frontback krqcmy Dequeue operation:

Implementing stacks, 1 abc Linked representation. All operations constant time, or O(1).

Implementing stacks, 2  An alternative is to use an array-based representation.  What are some advantages and disadvantages of an array-based representation? abc top

Array representation of stacks  But what to do when the array overflows?  Can we still get O(1) operations?  We could have a linked list of arrays.  Is there another way?

An idea  Let’s try doubling the size of the array every time it overflows.  In more detail:  Start off with an array of size n.  When the array overflows, allocate a new array of size 2n, copy all of the previous n elements to it.  Set n=2n, and then continue by using the new array.

A Big Hint  Whenever you see something doubling, immediately think of powers of 2:  2 0, 2 1, 2 2, 2 3, 2 4, … Opportunity for induction…

Question 1  In the worst case, what is the running time of the push operation?  I.e., how many copying operations might be needed?  Answer: O(n).  If a push() operation causes an overflow, then potentially all n elements on the stack must be copied.

Question 2  In the worst case, when starting with an empty stack, what is the average running time for all of the push operations in any given sequence of legal stack operations?

What contributes  What contributes to the running time?  The push itself  Possibility of creating a new array  Copying all of the elements to a new array Constant-time overhead This is the overhead that we have to worry about

Informal analysis  Let’s try counting a sequence of push operations, starting with array of size 0.  push: 0 copies (create new array of size 2 0 )  push: 1 copy (into a new array of size 2 1 )  push: 2 copies (into a new array of size 2 2 )  push push: 4 copies (into a new array of size 2 3 )  push push push push: 8 copies (into a new array of size 2 4 )

Informal analysis, cont’d copy operations are needed. So, on average, one copy is needed for every push operation. 2 n-1 +2 n-2 +2 n-3 …+2 0 =  2 n For 2 n push operations, a grand total of

Question 2, again  In the worst case, when starting with an empty stack, what is the average running time for all of the push operations in any given sequence of legal stack operations?  Answer: O(1)  Each push might require the creation of a new array plus, on average, a copy.

Amortized running time  We say that our array-based implementation of stacks runs in amortized constant (O(1)) time.  The J2SE java.util.ArrayList class is based on this representation.java.util.ArrayList

A question to ponder…  Question: How would you use an implementation of the Stack interface to implement the Queue interface?  What would be the running time of the operations?

A queue from two stacks f g h i j Enqueue: e d c b a Dequeue: What happens when the stack on the right becomes empty?