CS.7.A.Performance.Challenge
|
|
- Roger Preston
- 5 years ago
- Views:
Transcription
1 PA R T I : P R O G R A M M I G I J AVA PA R T I : P R O G R A M M I G I J AVA Computer Science Computer Science The challenge Empirical analysis Mathematical models Doubling method An Interdisciplinary Approach Section 4. Familiar examples ROBERT SEDGEWICK K E V I WAY E CS.7.A.Performance.Challenge The challenge (since the earliest days of computing machines) The challenge (modern version) Q. Will I be able to use my program to solve a large practical problem? As soon as an Analytic Engine exists, it will necessarily guide the future course of the science. Whenever any result is sought by its aid, the question will arise By what course of calculation can these results be arrived at by the machine in the shortest time? Charles Babbage Difference Engine #2 Designed by Charles Babbage, c. 848 Q. How many times do you have to turn the crank? Built by London Science Museum, 99 Q. If not, how might I understand its performance characteristics so as to improve it? Key insight (Knuth 97s). Use the scientific method to understand performance. 3 4
2 Three reasons to study program performance Will my program finish? When will my program finish? 2. To compare algorithms and implementations. Will this change make my program faster? How can I make my program faster? 3. To develop a basis for understanding the problem and for designing new algorithms Enables new technology. Enables new research. public class Gambler int stake = Integer.parseInt(args[]); int goal = Integer.parseInt(args[]); int trials = Integer.parseInt(args[2]); int wins = ; for (int t = ; t < trials; t++) int cash = stake; while (cash > && cash < goal) if (Math.random() <.5) cash++; else cash--; if (cash == goal) wins++; StdOut.print(wins + " wins of " + trials); -body simulation Brute-force algorithm uses 2 steps per time unit. Issue (97s): Too slow to address scientific problems of interest. Success story: Barnes-Hut algorithm uses log steps and enables new research. Andrew Appel PU '8 senior thesis 2 An algorithm is a method for solving a problem that is suitable for implementation as a computer program. limit on available time log problem size ( ) We study several algorithms later in this course. Taking more CS courses? You'll learn dozens of algorithms. 5 Another algorithm design success story 6 Quick aside: binary logarithms Discrete Fourier transform Def. The binary logarithm of a number (written lg ) is the number x satisfying 2x =. Goal: Break down waveform of samples into periodic components. Applications: digital signal processing, spectroscopy, or log2 Brute-force algorithm uses 2 steps. Issue (95s): Too slow to address commercial applications of interest. Success story: FFT algorithm uses log steps and enables new technology. lg Goal: Simulate gravitational interactions among bodies. time. To predict program behavior An algorithm design success story Q. How many recursive calls for convert()? John Tukey time A. Largest integer less than or equal to lg (written Frequently encountered values public static String convert(int ) if ( == ) return ""; return convert(/2) + ( % 2); 2 2 lg ). approximate value lg log 2 thousand million billion Prove by induction. Details in "sorting and searching" lecture. Fact. The number of bits in the binary representation of is + lg. limit on available time log Fact. Binary logarithms arise in the study of algorithms based on recursively solving problems half the size (divide-and-conquer algorithms), like convert, FFT and Barnes-Hut. problem size ( ) 7 8
3 An algorithmic challenge: 3-sum problem Three-sum implementation Three-sum. Given integers, enumerate the triples that sum to. public class ThreeSum public static int count(int[] a) /* See next slide. */ int[] a = StdIn.readAllInts(); StdOut.println(count(a)); % more 6ints.txt % java ThreeSum < 6ints.txt 3 Q. Can we solve this problem for = million? For simplicity, just count them Applications in computational geometry Find collinear points. Does one polygon fit inside another? Robot motion planning. [a surprisingly long list] 9 "Brute force" algorithm Process all possible triples. Increment counter when sum is. public static int count(int[] a) int = a.length; int cnt = ; for (int i = ; i < ; i++) for (int j = i+; j < ; j++) for (int k = j+; k < ; k++) if (a[i] + a[j] + a[k] == ) cnt++; return cnt; i a[i] Keep i < j < k to avoid processing each triple 6 times triples with i < j < k Q. How much time will this program take for = million? i j k a[i] a[j] a[k] PART I: PROGRAMMIG I JAVA PART I: PROGRAMMIG I JAVA Image sources The challenge Empirical analysis Mathematical models Doubling method Familiar examples CS.7.A.Performance.Challenge CS.7.B.Performance.Empirical
4 A first step in analyzing running time Empirical analysis Find representative inputs Run experiments Option : Collect actual input data. Option 2: Write a program to generate representative inputs. public class Generator // Generate integers in [-M, M) int M = Integer.parseInt(args[]); int = Integer.parseInt(args[]); for (int i = ; i < ; i++) StdOut.println(StdRandom.uniform(-M, M)); % java Generator % java Generator Start with a moderate input size. Replace println() in ThreeSum with this code. double start = System.currentTimeMillis() /.; int cnt = count(a); double now = System.currentTimeMillis() /.; StdOut.printf("%d (%.f seconds)\n", cnt, now - start); Measure and record running time. Double input size. Repeat. Tabulate and plot results. Tabulate and plot results 25 Run experiments 2 % java Generator java ThreeSum 59 ( seconds) time (seconds) Input generator for ThreeSum Measure running time % java Generator 2 java ThreeSum 522 (4 seconds) % java Generator 4 java ThreeSum 3992 (3 seconds) not much chance of a 3-sum % java Generator 8 java ThreeSum 393 (248 seconds) good chance of a 3-sum time (seconds) problem size ( ) 3 Aside: experimentation in CS 4 Data analysis is virtually free, particularly by comparison with other sciences. Curve fitting Plot on log-log scale. If points are on a straight line (often the case), a one million experiments power law holds a curve of the form a b fits. The exponent b is the slope of the line. Solve for a with the data. one experiment Chemistry log-log plot lg T 4.84 T lg Do the math x-intercept (use lg in anticipation of next step) 8 lgt = lga + 3lg log time (lg T) Biology Physics Computer Science 5 straight line of slope 3 2 Bottom line. o excuse for not running experiments to understand costs = a 83 substitute values from experiment a = 4.84 T = 4.84 solve for a 3 substitute 3 log problem size (lg ) 5 T = equation for straight line of slope 3 raise 2 to a power of both sides a 3 a curve that fits the data? 6
5 Prediction and verification Another hypothesis Hypothesis. Running time of ThreeSum is Prediction. Running time for = 6, will be 982 seconds. about half an hour 97s 2 time (seconds) (estimated ) seconds % java Generator 6 java ThreeSum 393 (985 seconds) VAX / seconds Q. How much time will this program take for = million? A. 484 million seconds (more than 5 years). 2s:,+ times faster Macbook Air 25 2 time (seconds) Hypothesis. Running times on different computers differ by only a constant factor. 7 8 PART I: PROGRAMMIG I JAVA PART I: PROGRAMMIG I JAVA Image sources The challenge Empirical analysis Mathematical models Doubling method Familiar examples CS.7.B.Performance.Empirical CS.7.C.Performance.Math
6 Mathematical models for running time Q. Can we write down an accurate formula for the running time of a computer program? A. (Prevailing wisdom, 96s) o, too complicated. A. (D. E. Knuth, 968 present) Yes! Determine the set of operations. Find the cost of each operation (depends on computer and system software). Find the frequency of execution of each operation (depends on algorithm and inputs). Total running time: sum of cost frequency for all operations. Warmup: -sum public static int count(int[] a) int = a.length; int cnt = ; for (int i = ; i < ; i++) if (a[i] == ) cnt++; return cnt; Q. Formula for total running time? ote that frequency of increments depends on input. operation cost frequency function call/return 2 ns variable declaration 2 ns 2 assignment ns 2 less than compare /2 ns + equal to compare /2 ns array access /2 ns increment /2 ns between and 2 representative estimates (with some poetic license); knowing exact values may require study and experimentation. Don Knuth 974 Turing Award 2 A. c nanoseconds, where c is between 2 and 2.5, depending on input. 22 Warmup: 2-sum Simplifying the calculations public static int count(int[] a) int = a.length; int cnt = ; for (int i = ; i < ; i++) for (int j = i+; j < ; j++) if (a[i] + a[j] == ) cnt++; return cnt; Q. Formula for total running time? operation cost frequency function call/return 2 ns variable declaration 2 ns + 2 assignment ns + 2 less than compare /2 ns ( + ) ( + 2)/2 equal to compare /2 ns ( )/2 array access /2 ns ( ) increment /2 ns between ( + )/2 and 2 exact counts tedious to derive # i < j = 2 ( ) = 2 Tilde notation Use only the fastest-growing term. Ignore the slower-growing terms. Def. f( ) ~ g( ) means f( )/g( ) as Ex. 5/ /4 + 53/2,253,276.5 for =, Rationale When is large, ignored terms are negligible. When is small, everything is negligible. ~ 5/4 2,25, for =,, within.3% Q. Formula for 2-sum running time when count is not large (typical case)? A. c 2 + c2 + c3 nanoseconds, where [complicated definitions]. A. ~ 5/4 2 nanoseconds. eliminate dependence on input 23 24
7 Mathematical model for 3-sum Context public static int count(int[] a) int = a.length; int cnt = ; for (int i = ; i < ; i++) for (int j = i+; j < ; j++) for (int k = j+; k < ; k++) if (a[i] + a[j] + a[k] == ) cnt++; return cnt; # i < j < k = operation cost frequency function call/return 2 ns variable declaration 2 ns ~ assignment ns ~ less than compare /2 ns ~ 3 /6 equal to compare /2 ns ~ 3 /6 array access /2 ns ~ 3 /2 increment /2 ns ~ 3 /6 Q. Formula for total running time when return value is not large (typical case)? 3 ( )( 2) = assumes count is not large Scientific method Observe some feature of the natural world. Hypothesize a model consistent with observations. Predict events using the hypothesis. Verify the predictions by making further observations. Validate by refining until hypothesis and observations agree. Empirical analysis of programs "Feature of natural world" is time taken by a program on a computer. Fit a curve to experimental data to get a formula for running time as a function of. Useful for predicting, but not explaining. Francis Bacon René Descartes John Stuart Mill Mathematical analysis of algorithms Analyze algorithm to develop a formula for running time as a function of. Useful for predicting and explaining. Might involve advanced mathematics. Applies to any computer. A. ~ 3 /2 nanoseconds. matches empirical hypothesis Good news. Mathematical models are easier to formulate in CS than in other sciences PART I: PROGRAMMIG I JAVA PART I: PROGRAMMIG I JAVA Image sources The challenge Empirical analysis Mathematical models Doubling method Familiar examples CS.7.C.Performance.Math CS.7.D.Performance.Doubling
8 Key questions and answers Doubling method Q. Is the running time of my program ~ a b seconds? Hypothesis. The running time of my program is T ~ a b. no need to calculate a (!) A. Yes, there's good chance of that. Might also have a (lg ) c factor. Consequence. As increases, T2/T approaches 2 b. Proof: ( ) = Q. How do you know? A. Computer scientists have applied such models for decades to many, many specific algorithms and applications. A. Programs are built from simple constructs (examples to follow). A. Real-world data is also often simply structured. A. Deep connections exist between such models and a wide variety of discrete structures (including some programs). 29 Doubling method Start with a moderate size. Measure and record running time. Double size. Repeat while you can afford it. Verify that ratios of running times approach 2 b. Predict by extrapolation: multiply by 2 b to estimate T2 and repeat. 3-sum example Bottom line. It is often easy to meet the challenge of predicting performance. T T/T/ = = = math model says running time should be a = 8 3 Order of growth Order of growth Def. If a function f() ~ ag( ) we say that g( ) is the order of growth of the function. Hypothesis. The order of growth of the running time of my program is b (log ) c. log instead of lg since constant base not relevant Hypothesis. Order of growth is a property of the algorithm, not the computer or the system. Evidence. Known to be true for many, many programs with simple and similar structure. Experimental validation When we execute a program on a computer that is X times faster, we expect the program to be X times faster. Explanation with mathematical model Machine- and system-dependent features of the model are all constants. 3 Linear () for (int i = ; i < ; i++) Logarithmic (log ) public static void f(int ) if ( == ) return; f(/2) Stay tuned for examples. Quadratic ( 2 ) for (int i = ; i < ; i++) for (int j = i+; j < ; j++) Linearithmic ( log ) public static void f(int ) if ( == ) return; f(/2) f(/2) for (int i = ; i < ; i++) Cubic ( 3 ) for (int i = ; i < ; i++) for (int j = i+; j < ; j++) for (int k = j+; k < ; k++) Exponential (2 ) public static void f(int ) if ( == ) return; f(-) f(-) ignore for practical purposes (infeasible for large ) 32
9 Order of growth classifications An important implication order of growth description function slope of line in log-log plot (b) factor for doubling method (2 b ) constant log-log plot 3 2 log Moore's Law. Computer power increases by a roughly a factor of 2 every 2 years. Q. My problem size also doubles every 2 years. How much do I need to spend to get my job done? logarithmic log a very common situation: weather prediction, transaction processing, cryptography linear 2 linearithmic log 2 quadratic cubic if input size doubles running time increases by this factor If math model gives order of growth, use doubling method to validate 2 b ratio. Problem size If not, use doubling method and solve for b = lg(t/t/2) to estimate order of growth to be b. Time 8T 4T 2T T K 2K 4K 8K log math model may have log factor Do the math T = a 3 T2 = (a/2)(2 ) 3 = 4a 3 = 4T running time today running time in 2 years A. You can't afford to use a quadratic algorithm (or worse) to address increasing problem sizes. now 2 years 4 years from now from now 2M years from now $X $X $X $X log $X $X $X $X 2 $X $2X $4X $2 M X 3 $X $4X $6X $4 M X Meeting the challenge Caveats My program is taking too long to finish. I'm going out to get a pizza. Mine, too. I'm going to run a doubling experiment. It is sometimes not so easy to meet the challenge of predicting performance. There are many other apps running on my computer! We need more terms in the math model: lg +? Hmmm. Still didn't finish. The experiment showed my program to have a higher order of growth than I expected. I found and fixed the bug. Time for some pizza! Your input model is too simple: My real input data is completely different. What happens when the leading term oscillates? Doubling experiments provide good insight on program performance Best practice to plan realistic experiments for debugging, anyway. Having some idea about performance is better than having no idea. Performance matters in many, many situations. Your machine model is too simple: My computer has parallel processors and a cache. Where s the log factor? a(2) b (lg(2)) c a b (lg ) c = 2 b + (lg ) Good news. Doubling method is robust in the face of many of these challenges. 2 b c 35 36
10 PART I: PROGRAMMIG I JAVA PART I: PROGRAMMIG I JAVA Image sources The challenge Empirical analysis Mathematical models Doubling hypothesis Familiar examples CS.7.D.Performance.Doubling CS.7.E.Performance.Examples Example: Gambler s ruin simulation Pop quiz on performance Q. How long to compute chance of doubling million dollars? public class Gambler int stake = Integer.parseInt(args[]); int goal = Integer.parseInt(args[]); int trials = Integer.parseInt(args[2]); double start = System.currentTimeMillis()/.; int wins = ; for (int i = ; i < trials; i++) int t = stake; while (t > && t < goal) if (Math.random() <.5) t++; else t--; if (t == goal) wins++; double now = System.currentTimeMillis()/.; StdOut.print(wins + " wins of " + trials); StdOut.printf(" (%.f seconds)\n", now - start); T T/T/ = = % java Gambler 2 53 wins of (4 seconds) % java Gambler wins of (7 seconds) % java Gambler wins of (56 seconds) % java Gambler wins of (286 seconds) math model says order of growth should be 2 Q. Let T be the running time of program Mystery and consider these experiments: public class Mystery int = Integer.parseInt(args[]); Q. Predict the running time for = 64,. Q. Estimate the order of growth. T (in seconds) T/T/ A. 4.8 million seconds (about 2 months). % java Gambler wins of (72 seconds) 39 4
11 Pop quiz on performance Another example: Coupon collector Q. Let T be the running time of program Mystery and consider these experiments. Q. How long to simulate collecting million coupons? T T/T/2 public class Mystery int = Integer.parseInt(args[]); Q. Predict the running time for = 64,. A. 248 seconds. T (in seconds) T/T/ = = = public class Collector int = Integer.parseInt(args[]); int trials = Integer.parseInt(args[]); int cardcnt = ; double start = System.currentTimeMillis()/.; for (int i = ; i < trials; i++) int valcnt = ; boolean[] found = new boolean[]; while (valcnt < ) int val = (int) (StdRandom() * ); cardcnt++; if (!found[val]) valcnt++; found[val] = true; double now = System.currentTimeMillis()/.; StdOut.printf( %d %.f,, *Math.log() *); StdOut.print(cardcnt/trials); StdOut.printf(" (%.f seconds)\n", now - start); = 63 2 % java Collector (7 seconds) % java Collector (4 seconds) math model says order of growth should be log % java Collector 5 Q. Estimate the order of growth (3 seconds) A. 2, since lg 4 = 2. 4 A. About minute. might run out of memory trying for billion % java Collector (66 seconds) 42 Analyzing typical memory requirements Summary A bit is or and the basic unit of memory. A byte is eight bits the smallest addressable unit. megabyte (MB) is about million bytes. gigabyte (GB) is about billion bytes. Use computational experiments, mathematical analysis, and the scientific method to learn whether your program might be useful to solve a large problem. Primitive-type values System-supported data structures (typical) Q. What if it's not fast enough? type bytes boolean ote: not bit type bytes int[] A. yes does it scale? no char 2 int 4 float 4 long 8 double 8 double[] int[][] ~ 4 2 double[][] ~ 8 2 String buy a new computer and solve bigger problems no learn a better algorithm found one? yes Example. 2-by-2 double array uses ~32MB. invent a better algorithm Plenty of new algorithms awaiting discovery. Example: Solve 3-sum efficiently 43 44
12 Case in point PA R T I : P R O G R A M M I G I J AVA ot so long ago, 2 CS grad students had a program to index and rank the web (to enable search). Image source yes does it scale? buy a new computer and solve bigger problems changing the world? maybe yes Larry Page and Sergey Brin no learn a better algorithm not yet no found one? yes PageRank (see Section.6) invent a better algorithm Lesson. Performance matters! PA R T I : P R O G R A M M I G I J AVA Computer Science Computer Science An Interdisciplinary Approach Section 4. ROBERT SEDGEWICK K E V I WAY E 45 CS.7.E.Performance.Examples
8. Performance Analysis
COMPUTER SCIENCE S E D G E W I C K / W A Y N E 8. Performance Analysis Section 4.1 http://introcs.cs.princeton.edu COMPUTER SCIENCE S E D G E W I C K / W A Y N E 8. Performance analysis The challenge Empirical
More information4.1 Performance. Running Time. The Challenge. Scientific Method
Running Time 4.1 Performance As soon as an Analytic Engine exists, it will necessarily guide the future course of the science. Whenever any result is sought by its aid, the question will arise by what
More informationRunning Time. Analytic Engine. Charles Babbage (1864) how many times do you have to turn the crank?
4.1 Performance Introduction to Programming in Java: An Interdisciplinary Approach Robert Sedgewick and Kevin Wayne Copyright 2002 2010 3/30/11 8:32 PM Running Time As soon as an Analytic Engine exists,
More information4.1 Performance. Running Time. The Challenge. Scientific Method. Reasons to Analyze Algorithms. Algorithmic Successes
Running Time 4.1 Performance As soon as an Analytic Engine exists, it will necessarily guide the future course of the science. Whenever any result is sought by its aid, the question will arise by what
More informationRunning Time. Analytic Engine. Charles Babbage (1864) how many times do you have to turn the crank?
4.1 Performance Introduction to Programming in Java: An Interdisciplinary Approach Robert Sedgewick and Kevin Wayne Copyright 2008 March 30, 2009 7:37 tt Running Time As soon as an Analytic Engine exists,
More informationCS 112 Introduction to Programming
Running Time CS 112 Introduction to Programming As soon as an Analytic Engine exists, it will necessarily guide the future course of the science. Whenever any result is sought by its aid, the question
More information4.1 Performance. Running Time. Scientific Method. Algorithmic Successes
Running Time 4.1 Performance As soon as an Analytic Engine exists, it will necessarily guide the future course of the science. Whenever any result is sought by its aid, the question will arise - By what
More information4.1 Performance Analysis
4.1 Performance Analysis Running Time As soon as an Analytic Engine exists, it will necessarily guide the future course of the science. Whenever any result is sought by its aid, the question will arise
More informationAnalysis of Algorithms
Running time Analysis of Algorithms As soon as an Analytic Engine exists, it will necessarily guide the future course of the science. Whenever any result is sought by its aid, the question will arise -
More information1.4 Analysis of Algorithms
1.4 Analysis of Algorithms Cast of characters Programmer needs to develop a working solution. Client wants to solve problem efficiently. Student might play any or all of these roles someday. observations
More information1.4 Analysis of Algorithms
1.4 Analysis of Algorithms observations mathematical models order-of-growth classifications dependencies on inputs memory Algorithms, 4 th Edition Robert Sedgewick and Kevin Wayne Copyright 2002 2010 September
More information4.1, 4.2 Performance, with Sorting
1 4.1, 4.2 Performance, with Sorting Running Time As soon as an Analytic Engine exists, it will necessarily guide the future course of the science. Whenever any result is sought by its aid, the question
More informationData Structures 1.4 ANALYSIS OF ALGORITHMS. introduction observations mathematical models order-of-growth classifications theory of algorithms memory
Data Structures 1.4 ANALYSIS OF ALGORITHMS introduction observations mathematical models order-of-growth classifications theory of algorithms memory 1.4 ANALYSIS OF ALGORITHMS introduction observations
More informationAlgorithms. Algorithms. Algorithms 1.4 ANALYSIS OF ALGORITHMS. introduction. introduction observations. observations
Algorithms ROBERT SEDGEWICK KEVI WAYE.4 AALYSIS OF ALGORITHMS.4 AALYSIS OF ALGORITHMS introduction introduction observations observations Algorithms F O U R T H E D I T I O mathematical models order-of-growth
More informationAlgorithms 1.4 ANALYSIS OF ALGORITHMS. observations mathematical models order-of-growth classifications dependencies on inputs memory
1.4 ANALYSIS OF ALGORITHMS Algorithms F O U R T H E D I T I O N observations mathematical models order-of-growth classifications dependencies on inputs memory R O B E R T S E D G E W I C K K E V I N W
More informationAlgorithms. Algorithms 1.4 ANALYSIS OF ALGORITHMS
ROBERT SEDGEWICK KEVIN WAYNE Algorithms ROBERT SEDGEWICK KEVIN WAYNE 1.4 ANALYSIS OF ALGORITHMS Algorithms F O U R T H E D I T I O N http://algs4.cs.princeton.edu introduction observations mathematical
More informationhttp://www.flickr.com/photos/exoticcarlife/3270764550/ http://www.flickr.com/photos/roel1943/5436844655/ Performance analysis Why we care What we measure and how How functions grow Empirical analysis The
More informationAlgorithms. Algorithms. Algorithms 1.4 ANALYSIS OF ALGORITHMS. introduction. introduction observations. observations
Algorithms ROBERT SEDGEWICK KEVI WAYE.4 AALYSIS OF ALGORITHMS.4 AALYSIS OF ALGORITHMS introduction introduction observations observations Algorithms F O U R T H E D I T I O mathematical models order-of-growth
More informationANALYSIS OF ALGORITHMS
BBM 202 - ALGORITHMS DEPT. OF COMPUTER EGIEERIG Analysis of Algorithms Observations Mathematical models Order-of-growth classifications Dependencies on inputs Memory TODAY AALYSIS OF ALGORITHMS Acknowledgement:
More informationPerformance analysis.
Performance analysis http://xkcd.com/399/ CSCI 136: Fundamentals of Computer Science II Keith Vertanen Copyright 2011 Performance analysis Overview Why we care What we measure and how How functions grow
More informationAlgorithms and Data Structures, Fall Introduction. Rasmus Pagh. Based on slides by Kevin Wayne, Princeton. Monday, August 29, 11
Algorithms and Data Structures, Fall 2011 Introduction Rasmus Pagh Based on slides by Kevin Wayne, Princeton Why study algorithms? Their impact is broad and far-reaching. Internet. Web search, packet routing,
More informationAlgorithms. Algorithms. Algorithms 1.4 ANALYSIS OF ALGORITHMS
Announcements Algorithms ROBERT SEDGEWICK KEVI WAYE First programming assignment. Due Tuesday at pm. Try electronic submission system today. "Check All Submitted Files. will perform checks on your code
More information1.4 ANALYSIS OF ALGORITHMS
1.4 ANALYSIS OF ALGORITHMS AS people gain experience using computers, they use them to solve difficult problems or to process large amounts of data and are invariably led to questions like these: How long
More informationAnalysis of Algorithms 1 / 18
Analysis of Algorithms 1 / 18 Outline 1 Complexity of Algorithms 2 Time Complexity 3 Space Complexity 2 / 18 Complexity of Algorithms Questions that arise when we write programs that process large amounts
More informationPerformance. CSCI 135: Fundamentals of Computer Science Keith Vertanen. h"p://
Performance h"p://www.flickr.com/photos/exo3ccarlife/3270764550/ h"p://www.flickr.com/photos/roel1943/5436844655/ CSCI 135: Fundamentals of Computer Science Keith Vertanen Performance analysis Overview
More informationSorting. 4.2 Sorting and Searching. Sorting. Sorting. Insertion Sort. Sorting. Sorting problem. Rearrange N items in ascending order.
4.2 and Searching pentrust.org Introduction to Programming in Java: An Interdisciplinary Approach Robert Sedgewick and Kevin Wayne Copyright 2002 2010 23/2/2012 15:04:54 pentrust.org pentrust.org shanghaiscrap.org
More informationAlgorithms. Algorithms. Algorithms 1.4 ANALYSIS OF ALGORITHMS
Announcements Algorithms ROBERT SEDGEWICK KEVI WAYE First programming assignment. Due Tomorrow at :00pm. Try electronic submission system today. "Check All Submitted Files. will perform checks on your
More informationCS/COE 1501
CS/COE 1501 www.cs.pitt.edu/~nlf4/cs1501/ Introduction Meta-notes These notes are intended for use by students in CS1501 at the University of Pittsburgh. They are provided free of charge and may not be
More informationCS/COE 1501 cs.pitt.edu/~bill/1501/ Introduction
CS/COE 1501 cs.pitt.edu/~bill/1501/ Introduction Meta-notes These notes are intended for use by students in CS1501 at the University of Pittsburgh. They are provided free of charge and may not be sold
More informationCOMPUTER SCIENCE. 4. Arrays. Section 1.4.
COMPUTER SCIENCE S E D G E W I C K / W A Y N E 4. Arrays Section 1.4 http://introcs.cs.princeton.edu Basic building blocks for programming any program you might want to write objects functions and modules
More informationWeek 12: Running Time and Performance
Week 12: Running Time and Performance 1 Most of the problems you have written in this class run in a few seconds or less Some kinds of programs can take much longer: Chess algorithms (Deep Blue) Routing
More informationCS 112 Introduction to Programming
CS 112 Introduction to Programming (Spring 2012) Lecture #9: Arrays Zhong Shao Department of Computer Science Yale University Office: 314 Watson http://flint.cs.yale.edu/cs112 Acknowledgements: some slides
More information4.2 Sorting and Searching. Section 4.2
4.2 Sorting and Searching 1 Sequential Search Scan through array, looking for key. Search hit: return array index. Search miss: return -1. public static int search(string key, String[] a) { int N = a.length;
More information1.4 Arrays. A Foundation for Programming. Arrays. Many Variables of the Same Type. This lecture. Store and manipulate huge quantities of data.
A Foundation for Programming 1.4 Arrays any program you might want to write objects functions and modules graphics, sound, and image I/O arrays store and manipulate huge quantities of data conditionals
More information1.4 Arrays. A Foundation for Programming. Many Variables of the Same Type. Arrays. !!! any program you might want to write
A Foundation for Programming 1.4 Arrays any program you might want to write objects functions and modules graphics, sound, and image I/O arrays store and manipulate huge quantities of data conditionals
More informationCS240 Fall Mike Lam, Professor. Algorithm Analysis
CS240 Fall 2014 Mike Lam, Professor Algorithm Analysis HW1 Grades are Posted Grades were generally good Check my comments! Come talk to me if you have any questions PA1 is Due 9/17 @ noon Web-CAT submission
More information1.3 Conditionals and Loops
A Foundation for Programming 1.3 Conditionals and Loops any program you might want to write objects functions and modules graphics, sound, and image I/O arrays conditionals and loops Math primitive data
More information3. Conditionals and loops
COMPUTER SCIENCE S E D G E W I C K / W A Y N E 3. Conditionals and loops Section 1.3 http://introcs.cs.princeton.edu COMPUTER SCIENCE S E D G E W I C K / W A Y N E 3. Conditionals & Loops Conditionals:
More informationCS/ENGRD 2110 Object-Oriented Programming and Data Structures Spring 2012 Thorsten Joachims. Lecture 10: Asymptotic Complexity and
CS/ENGRD 2110 Object-Oriented Programming and Data Structures Spring 2012 Thorsten Joachims Lecture 10: Asymptotic Complexity and What Makes a Good Algorithm? Suppose you have two possible algorithms or
More informationIntegrated Math I. IM1.1.3 Understand and use the distributive, associative, and commutative properties.
Standard 1: Number Sense and Computation Students simplify and compare expressions. They use rational exponents and simplify square roots. IM1.1.1 Compare real number expressions. IM1.1.2 Simplify square
More informationComputational biology course IST 2015/2016
Computational biology course IST 2015/2016 Introduc)on to Algorithms! Algorithms: problem- solving methods suitable for implementation as a computer program! Data structures: objects created to organize
More informationCS240 Fall Mike Lam, Professor. Algorithm Analysis
CS240 Fall 2014 Mike Lam, Professor Algorithm Analysis Algorithm Analysis Motivation: what and why Mathematical functions Comparative & asymptotic analysis Big-O notation ("Big-Oh" in textbook) Analyzing
More information3. Conditionals & Loops
Context: basic building blocks for programming any program you might want to write objects functions and modules graphics, sound, and image I/O arrays conditionals and loops conditionals loops Math primitive
More informationCS 580: Algorithm Design and Analysis. Jeremiah Blocki Purdue University Spring 2018
CS 580: Algorithm Design and Analysis Jeremiah Blocki Purdue University Spring 2018 Recap: Stable Matching Problem Definition of a Stable Matching Stable Roomate Matching Problem Stable matching does not
More information3. Conditionals & Loops
COMPUTER SCIENCE S E D G E W I C K / W A Y N E 3. Conditionals & Loops Section 1.3 http://introcs.cs.princeton.edu Context: basic building blocks for programming any program you might want to write objects
More informationChoice of C++ as Language
EECS 281: Data Structures and Algorithms Principles of Algorithm Analysis Choice of C++ as Language All algorithms implemented in this book are in C++, but principles are language independent That is,
More information1.3 Conditionals and Loops
.3 Conditionals and Loops Introduction to Programming in Java: An Interdisciplinary Approach Robert Sedgewick and Kevin Wayne Copyright 2008 February 04, 2008 0:00 AM A Foundation for Programming A Foundation
More informationDebugging [continued]
1 Debugging [continued] Admiral Grace Murray Hopper http://www.history.navy.mil/photos/images/h96000/h96566kc.htm 2 Debugging Your Program Debugging Your Program. [summary] 1. Edit the program (type in
More informationLecture 3: Loops. While Loops. While Loops: Newton-Raphson Method. While Loops: Powers of Two
While Loops Lecture 3: Loops The while loop is a common repetition structure. Check loop-continuation condition. Execute a sequence of statements. Repeat. while (boolean expression) statement; while loop
More informationAlgorithmic Analysis. Go go Big O(h)!
Algorithmic Analysis Go go Big O(h)! 1 Corresponding Book Sections Pearson: Chapter 6, Sections 1-3 Data Structures: 4.1-4.2.5 2 What is an Algorithm? Informally, any well defined computational procedure
More informationLecture 3: Loops. While Loops. While Loops: Powers of Two. While Loops: Newton-Raphson Method
While Loops Lecture : Loops The while loop is a common repetition structure. Check loop-continuation condition. Execute a sequence of statements. Repeat. while (boolean expression) statement; while loop
More informationDebugging [continued]
Debugging [continued] Admiral Grace Murray Hopper http://www.history.navy.mil/photos/images/h96000/h96566kc.htm 1 2 Debugging Your Program Debugging: Where we left off Debugging Your Program. [summary]
More information1.1 Your First Program
1.1 Your First Program Introduction to Programming in Java: An Interdisciplinary Approach Robert Sedgewick and Kevin Wayne Copyright 2002 2010 1/29/11 6:37 AM! Why Programming? Why programming? Need to
More informationData Structures Lecture 8
Fall 2017 Fang Yu Software Security Lab. Dept. Management Information Systems, National Chengchi University Data Structures Lecture 8 Recap What should you have learned? Basic java programming skills Object-oriented
More informationMeasuring algorithm efficiency
CMPT 225 Measuring algorithm efficiency Timing Counting Cost functions Cases Best case Average case Worst case Searching Sorting O Notation O notation's mathematical basis O notation classes and notations
More information! 52 playing cards in a deck. ! 5 thousand undergrads at Princeton. ! 1 million characters in a book. ! 10 million audio samples in an MP3 file.
Arrays 1.4 Arrays This lecture. Store and manipulate huge quantities of data. Array. Indexed sequence of values of the same type. Examples.! 52 playing cards in a deck.! 5 thousand undergrads at Princeton.!
More information2.3 Flow Control. Flow-Of-Control. If-Else: Leap Year. If-Else
Flow-Of-Control 2.3 Flow Control Flow-of-control. Sequence of statements that are actually executed in a program. Conditionals and loops: enable us to harness power of the computer. statement 1 boolean
More information1.1 Your First Program
Why Programming? 1.1 Your First Program Why programming? Need to tell computer what to do. Please simulate the motion of N heavenly bodies, subject to Newton s laws of motion and gravity. Prepackaged software
More informationIntroduction to Computer Science
Introduction to Computer Science Program Analysis Ryan Stansifer Department of Computer Sciences Florida Institute of Technology Melbourne, Florida USA 32901 http://www.cs.fit.edu/ ryan/ 24 April 2017
More informationMergeSort, Recurrences, Asymptotic Analysis Scribe: Michael P. Kim Date: April 1, 2015
CS161, Lecture 2 MergeSort, Recurrences, Asymptotic Analysis Scribe: Michael P. Kim Date: April 1, 2015 1 Introduction Today, we will introduce a fundamental algorithm design paradigm, Divide-And-Conquer,
More informationCS 112 Introduction to Programming
CS 112 Introduction to Programming (Spring 2012) Lecture #5: Conditionals and Loops Zhong Shao Department of Computer Science Yale University Office: 314 Watson http://flint.cs.yale.edu/cs112 Acknowledgements:
More information1/16/12. CS 112 Introduction to Programming. A Foundation for Programming. (Spring 2012) Lecture #4: Built-in Types of Data. The Computer s View
1/16/12 A Foundation for Programming CS 112 Introduction to Programming (Spring 2012) any program you might want to write Lecture #4: Built-in Types of Data objects Zhong Shao methods and classes graphics,
More informationAlgorithms and Data Structures
Algorithm Analysis Page 1 - Algorithm Analysis Dr. Fall 2008 Algorithm Analysis Page 2 Outline Textbook Overview Analysis of Algorithm Pseudo-Code and Primitive Operations Growth Rate and Big-Oh Notation
More informationBiostatistics 615/815 - Lecture 2 Introduction to C++ Programming
Biostatistics 615/815 - Lecture 2 Introduction to C++ Programming Hyun Min Kang September 6th, 2012 Hyun Min Kang Biostatistics 615/815 - Lecture 2 September 6th, 2012 1 / 31 Last Lecture Algorithms are
More information1.3 Conditionals and Loops. 1.3 Conditionals and Loops. Conditionals and Loops
1.3 Conditionals and Loops any program you might want to write objects functions and modules graphics, sound, and image I/O arrays conditionals and loops Math primitive data types text I/O assignment statements
More informationPROGRAM EFFICIENCY & COMPLEXITY ANALYSIS
Lecture 03-04 PROGRAM EFFICIENCY & COMPLEXITY ANALYSIS By: Dr. Zahoor Jan 1 ALGORITHM DEFINITION A finite set of statements that guarantees an optimal solution in finite interval of time 2 GOOD ALGORITHMS?
More informationAnalysis of Algorithms. 5-Dec-16
Analysis of Algorithms 5-Dec-16 Time and space To analyze an algorithm means: developing a formula for predicting how fast an algorithm is, based on the size of the input (time complexity), and/or developing
More informationMath 340 Fall 2014, Victor Matveev. Binary system, round-off errors, loss of significance, and double precision accuracy.
Math 340 Fall 2014, Victor Matveev Binary system, round-off errors, loss of significance, and double precision accuracy. 1. Bits and the binary number system A bit is one digit in a binary representation
More informationAnalysis of Algorithms Part I: Analyzing a pseudo-code
Analysis of Algorithms Part I: Analyzing a pseudo-code Introduction Pseudo-code representation of an algorithm Analyzing algorithms Measuring the running time and memory size of an algorithm Calculating
More informationCS 310: Order Notation (aka Big-O and friends)
CS 310: Order Notation (aka Big-O and friends) Chris Kauffman Week 1-2 Logistics At Home Read Weiss Ch 1-4: Java Review Read Weiss Ch 5: Big-O Get your java environment set up Compile/Run code for Max
More informationLecture 2: Intro to Java
Why Programming? Lecture 2: Intro to Java Idealized computer. "Please simulate the motion of a system of N heavenly bodies, subject to Newton's laws of motion and gravity." Prepackaged software solutions.
More informationMobile Computing Professor Pushpendra Singh Indraprastha Institute of Information Technology Delhi Java Basics Lecture 02
Mobile Computing Professor Pushpendra Singh Indraprastha Institute of Information Technology Delhi Java Basics Lecture 02 Hello, in this lecture we will learn about some fundamentals concepts of java.
More information1.1 Your First Program
Why Programming? Idealized computer. "Please simulate the motion of a system of N heavenly bodies, subject to Newton's laws of motion and gravity." 1.1 Your First Program Prepackaged software solutions.
More informationcsci 210: Data Structures Program Analysis
csci 210: Data Structures Program Analysis Summary Summary analysis of algorithms asymptotic analysis and notation big-o big-omega big-theta commonly used functions discrete math refresher Analysis of
More informationLecture Notes for Chapter 2: Getting Started
Instant download and all chapters Instructor's Manual Introduction To Algorithms 2nd Edition Thomas H. Cormen, Clara Lee, Erica Lin https://testbankdata.com/download/instructors-manual-introduction-algorithms-2ndedition-thomas-h-cormen-clara-lee-erica-lin/
More information10/5/2016. Comparing Algorithms. Analyzing Code ( worst case ) Example. Analyzing Code. Binary Search. Linear Search
10/5/2016 CSE373: Data Structures and Algorithms Asymptotic Analysis (Big O,, and ) Steve Tanimoto Autumn 2016 This lecture material represents the work of multiple instructors at the University of Washington.
More informationMidterm CSE 21 Spring 2012
Signature Name Student ID Midterm CSE 21 Spring 2012 Page 1 Page 2 Page 3 Page 4 Page 5 Page 6 _ (20 points) _ (15 points) _ (13 points) _ (23 points) _ (10 points) _ (8 points) Total _ (89 points) (84
More informationThe type of all data used in a C (or C++) program must be specified
The type of all data used in a C (or C++) program must be specified A data type is a description of the data being represented That is, a set of possible values and a set of operations on those values
More informationChapter Fourteen Bonus Lessons: Algorithms and Efficiency
: Algorithms and Efficiency The following lessons take a deeper look at Chapter 14 topics regarding algorithms, efficiency, and Big O measurements. They can be completed by AP students after Chapter 14.
More information1.3 Conditionals and Loops
1.3 Conditionals and Loops Introduction to Programming in Java: An Interdisciplinary Approach Robert Sedgewick and Kevin Wayne Copyright 2002 2010 15/1/2013 22:16:24 A Foundation for Programming any program
More informationMergeSort, Recurrences, Asymptotic Analysis Scribe: Michael P. Kim Date: September 28, 2016 Edited by Ofir Geri
CS161, Lecture 2 MergeSort, Recurrences, Asymptotic Analysis Scribe: Michael P. Kim Date: September 28, 2016 Edited by Ofir Geri 1 Introduction Today, we will introduce a fundamental algorithm design paradigm,
More informationOrganisation. Assessment
Week 1 s s Getting Started 1 3 4 5 - - Lecturer Dr Lectures Tuesday 1-13 Fulton House Lecture room Tuesday 15-16 Fulton House Lecture room Thursday 11-1 Fulton House Lecture room Friday 10-11 Glyndwr C
More information1.3 Conditionals and Loops
1 1.3 Conditionals and Loops any program you might want to write objects functions and modules graphics, sound, and image I/O arrays conditionals and loops to infinity and beyond Math primitive data types
More information1.1 Your First Program
1.1 Your First Program Introduction to Programming in Java: An Interdisciplinary Approach Robert Sedgewick and Kevin Wayne Copyright 2002 2010 5/20/2013 9:37:22 AM Why Programming? Why programming? Need
More informationAlgorithm. Lecture3: Algorithm Analysis. Empirical Analysis. Algorithm Performance
Algorithm (03F) Lecture3: Algorithm Analysis A step by step procedure to solve a problem Start from an initial state and input Proceed through a finite number of successive states Stop when reaching a
More information1.3 Conditionals and Loops
A Foundation for Programming 1.3 Conditionals and Loops any program you might want to write objects functions and modules graphics, sound, and image I/O arrays conditionals and loops Math primitive data
More informationChapter 1 Programming: A General Overview
Introduction Chapter 1 Programming: A General Overview This class is an introduction to the design, implementation, and analysis of algorithms. examples: sorting large amounts of data organizing information
More informationAlgorithm Analysis CISC4080 CIS, Fordham Univ. Instructor: X. Zhang
Algorithm Analysis CISC4080 CIS, Fordham Univ. Instructor: X. Zhang Last class Review some algorithms learned in previous classes idea => pseudocode => implementation Correctness? Three sorting algorithms:
More informationasymptotic growth rate or order compare two functions, but ignore constant factors, small inputs
Big-Oh 1 asymptotic growth rate or order 2 compare two functions, but ignore constant factors, small inputs asymptotic growth rate or order 2 compare two functions, but ignore constant factors, small inputs
More information2.3 Recursion. Overview. Mathematical Induction. What is recursion? When one function calls itself directly or indirectly.
2.3 Recursion Overview Mathematical Induction What is recursion? When one function calls itself directly or indirectly. Why learn recursion? New mode of thinking. Powerful programming paradigm. Many computations
More informationAdvanced Algorithms and Data Structures
Advanced Algorithms and Data Structures Prof. Tapio Elomaa Course Basics A new 7 credit unit course Replaces OHJ-2156 Analysis of Algorithms We take things a bit further than OHJ-2156 We will assume familiarity
More informationComputer Science 210 Data Structures Siena College Fall Topic Notes: Complexity and Asymptotic Analysis
Computer Science 210 Data Structures Siena College Fall 2017 Topic Notes: Complexity and Asymptotic Analysis Consider the abstract data type, the Vector or ArrayList. This structure affords us the opportunity
More informationChecking for duplicates Maximum density Battling computers and algorithms Barometer Instructions Big O expressions. John Edgar 2
CMPT 125 Checking for duplicates Maximum density Battling computers and algorithms Barometer Instructions Big O expressions John Edgar 2 Write a function to determine if an array contains duplicates int
More informationFloating Point. CSC207 Fall 2017
Floating Point CSC207 Fall 2017 Ariane 5 Rocket Launch Ariane 5 rocket explosion In 1996, the European Space Agency s Ariane 5 rocket exploded 40 seconds after launch. During conversion of a 64-bit to
More informationAnalysis of algorithms
Analysis of algorithms Time and space To analyze an algorithm means: developing a formula for predicting how fast an algorithm is, based on the size of the input (time complexity), and/or developing a
More informationLecture 2: Intro to Java
Why Java? Lecture 2: Intro to Java Java features. Widely available. Widely used. Variety of automatic checks for mistakes in programs. Embraces full set of modern abstractions. 2 Why Java? Why Java? Java
More informationChapter 1 Programming: A General Overview
Chapter 1 Programming: A General Overview 2 Introduction This class is an introduction to the design, implementation, and analysis of algorithms. Examples: sorting large amounts of data organizing information
More informationIntroduction to Computer Science
Introduction to Computer Science Program Analysis Ryan Stansifer Department of Computer Sciences Florida Institute of Technology Melbourne, Florida USA 32901 http://www.cs.fit.edu/ ryan/ 8 December 2017
More informationLecture T5: Analysis of Algorithm
Lecture T5: Analysis of Algorithm Overview Lecture T4: What is an algorithm? Turing machine. Is it possible, in principle, to write a program to solve any problem? No. Halting problem and others are unsolvable.
More informationIntro. Speed V Growth
Intro Good code is two things. It's elegant, and it's fast. In other words, we got a need for speed. We want to find out what's fast, what's slow, and what we can optimize. First, we'll take a tour of
More information