Algorithms. Algorithms. Algorithms 1.4 ANALYSIS OF ALGORITHMS. introduction. introduction observations. observations
|
|
- Shauna Lawrence
- 6 years ago
- Views:
Transcription
1 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 classifications Algorithms mathematical models order-of-growth classifications ROBERT SEDGEWICK KEVI WAYE memory ROBERT SEDGEWICK KEVI WAYE memory Cast of characters Running time Programmer needs to develop a working solution. 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 (864) Client wants to solve problem efficiently. Student might play any or all of these roles someday. how many times do you have to turn the crank? Theoretician wants to understand. Analytic Engine 3 4
2 Reasons to analyze algorithms Some algorithmic successes Predict performance. Compare algorithms. Provide guarantees. this course (COS 6) Discrete Fourier transform. Break down waveform of samples into periodic components. Applications: DVD, JPEG, MRI, astrophysics,. Brute force: steps. Friedrich FFT algorithm: log steps, enables new technology. Gauss 805 Understand theoretical basis. theory of algorithms (COS 43) time 64T quadratic Primary practical reason: avoid performance bugs. 3T client gets poor performance because programmer did not understand performance characteristics 6T 8T size linearithmic linear K K 4K 8K 5 6 Some algorithmic successes The challenge -body simulation. Simulate gravitational interactions among bodies. Brute force: steps. Barnes-Hut algorithm: log steps, enables new research. Andrew Appel PU '8 Q. Will my program be able to solve a large practical input? Why is my program so slow? Why does it run out of memory? time 64T quadratic 3T 6T 8T size linearithmic linear K K 4K 8K Insight. [Knuth 970s] Use scientific method to understand performance. 7 8
3 Scientific method applied to analysis of algorithms A framework for predicting performance and comparing algorithms. Scientific method. Observe some feature of the natural world. Hypothesize a model that is consistent with the observations. Predict events using the hypothesis. Verify the predictions by making further observations. Validate by repeating until the hypothesis and observations agree. Principles. Experiments must be reproducible. Hypotheses must be falsifiable. Algorithms ROBERT SEDGEWICK KEVI WAYE AALYSIS OF ALGORITHMS introduction observations mathematical models order-of-growth classifications memory Feature of the natural world. Computer itself. 9 Example: 3-SUM 3-SUM: brute-force algorithm 3-SUM. Given distinct integers, how many triples sum to exactly zero? % more 8ints.txt % java ThreeSum 8ints.txt a[i] a[j] a[k] sum public class ThreeSum public static int count(int[] a) int = a.length; for (int i = 0; i < ; i++) for (int j = i+; j < ; j++) for (int k = j+; k < ; k++) if (a[i] + a[j] + a[k] == 0) return count; check each triple for simplicity, ignore integer overflow Context. Deeply related to problems in computational geometry. public static void main(string[] args) In in = new In(args[0]); int[] a = in.readallints(); StdOut.println(count(a));
4 Measuring the running time Measuring the running time Q. How to time a program? A. Manual. % java ThreeSum Kints.txt tick tick tick Q. How to time a program? A. Automatic. 70 % java ThreeSum Kints.txt 58 % java ThreeSum 4Kints.txt public class Stopwatch Stopwatch() (part of stdlib.jar ) create a new stopwatch double elapsedtime() time since creation (in seconds) public static void main(string[] args) In in = new In(args[0]); int[] a = in.readallints(); Stopwatch stopwatch = new Stopwatch(); StdOut.println(ThreeSum.count(a)); client code double time = stopwatch.elapsedtime(); StdOut.println("elapsed time " + time); 4 Empirical analysis Empirical analysis Run the program for various input sizes and measure running time. Run the program for various input sizes and measure running time. time (seconds) ,000 0., , , ,000? 5 6
5 Data analysis Data analysis Standard plot. Plot running time T () vs. input size. Log-log plot. Plot running time T () vs. input size using log-log scale. standard plot running time T() log-log plot lg(t()) 3 orders of magnitude straight line of slope 3 lg(t ()) = b lg + c b =.999 c = T () = a b, where a = c. 0 K K 4K 8K lg K K 4K 8K problem size Regression. Fit straight line through data points: a b. power law slope Hypothesis. The running time is about seconds. 7 8 Prediction and validation Doubling hypothesis Hypothesis. The running time is about seconds. Doubling hypothesis. Quick way to estimate b in a power-law relationship. Predictions. 5.0 seconds for = 8, seconds for = 6,000. "order of growth" of running time is about 3 [stay tuned] Run program, doubling the size of the input. time (seconds) ratio lg ratio T () T () = a()b a b = b Observations. time (seconds), , , , , , lg (6.4 / 0.8) = 3.0 8, , validates hypothesis! seems to converge to a constant b 3 Hypothesis. Running time is about a b with b = lg ratio. Caveat. Cannot identify logarithmic factors with doubling hypothesis. 9 0
6 Doubling hypothesis Experimental algorithmics Doubling hypothesis. Quick way to estimate b in a power-law relationship. Q. How to estimate a (assuming we know b)? A. Run the program (for a sufficient large value of ) and solve for a. time (seconds) 8, = a , a = , System independent effects. Algorithm. Input data. System dependent effects. Hardware: CPU, memory, cache, Software: compiler, interpreter, garbage collector, determines exponent b in power law System: operating system, network, other apps, determines constant a in power law Hypothesis. Running time is about seconds. Bad news. Difficult to get precise measurements. Good news. Much easier and cheaper than other sciences. almost identical hypothesis to one obtained via linear regression e.g., can run huge number of experiments Mathematical models for running time.4 AALYSIS OF ALGORITHMS Total running time: sum of cost frequency for all operations. eed to analyze program to determine set of operations. Cost depends on machine, compiler. Frequency depends on algorithm, input data. Algorithms ROBERT SEDGEWICK KEVI WAYE introduction observations mathematical models order-of-growth classifications memory Donald Knuth 974 Turing Award In principle, accurate mathematical models are available. 4
7 Cost of basic operations Cost of basic operations Challenge. How to estimate constants. Observation. Most primitive operations take constant time. operation example nanoseconds integer add a + b. integer multiply a * b.4 integer divide a / b 5.4 floating-point add a + b 4.6 floating-point multiply a * b 4. floating-point divide a / b 3.5 sine Math.sin(theta) 9.3 operation example nanoseconds variable declaration int a c assignment statement a = b c integer compare a < b c 3 array element access a[i] c 4 array length a.length c 5 D array allocation new int[] c 6 D array allocation new int[][] c 7 arctangent Math.atan(y, x) Running OS X on Macbook Pro.GHz with GB RAM Caveat. on-primitive operations often take more than constant time. 5 novice mistake: abusive string concatenation 6 Example: -SUM Example: -SUM Q. How many instructions as a function of input size? Q. How many instructions as a function of input size? for (int i = 0; i < ; i++) if (a[i] == 0) for (int i = 0; i < ; i++) for (int j = i+; j < ; j++) if (a[i] + a[j] == 0) operation frequency array accesses Pf. [ n even] ( ) = ( ) = variable declaration assignment statement less than compare + equal to compare array access increment to ( ) = half of square half of diagonal 8
8 String theory infinite sum Example: -SUM = Q. How many instructions as a function of input size? for (int i = 0; i < ; i++) for (int j = i+; j < ; j++) if (a[i] + a[j] == 0) operation frequency ( ) = ( ) = variable declaration + assignment statement + less than compare ½ ( + ) ( + ) equal to compare ½ ( ) array access ( ) tedious to count exactly increment ½ ( ) to ( ) 9 30 Simplifying the calculations Simplification : cost model It is convenient to have a measure of the amount of work involved in a computing process, even though it be a very crude one. We may count up the number of times that various elementary operations are applied in the whole process and then given them various weights. We might, for instance, count the number of additions, subtractions, multiplications, divisions, recording of numbers, and extractions of figures from tables. In the case of computing with matrices most of the work consists of multiplications and writing down numbers, and we shall therefore only attempt to count the number of multiplications and recordings. Alan Turing Cost model. Use some basic operation as a proxy for running time. for (int i = 0; i < ; i++) for (int j = i+; j < ; j++) if (a[i] + a[j] == 0) operation frequency ( ) = ( ) = ROUDIG-OFF ERRORS I MATRIX PROCESSES By A. M. TURIG ational Physical Laboratory, Teddington, Middlesex) [Received 4 ovember 947] SUMMARY A number of methods of solving sets of linear equations and inverting matrices are discussed. The theory of the rounding-off errors involved is investigated for some of the methods. In all cases examined, including the well-known 'Gauss elimination process', it is found that the errors are normally quite moderate: no exponential build-up need occur. variable declaration + assignment statement + less than compare ½ ( + ) ( + ) equal to compare ½ ( ) array access ( ) increment ½ ( ) to ( ) cost model = array accesses (we assume compiler/jvm do not optimize any array accesses away!) 3 3
9 Simplification : tilde notation Estimate running time (or memory) as a function of input size. Ignore lower order terms. when is large, terms are negligible when is small, we don't care 3 /6 Simplification : tilde notation Estimate running time (or memory) as a function of input size. Ignore lower order terms. when is large, terms are negligible when is small, we don't care Ex. ⅙ ! ~ ⅙ 3 Ex. ⅙ /3 + 56! ~ ⅙ 3 66,666,667 3 /6 / + /3 Ex 3. ⅙ 3 - ½ + ⅓! ~ ⅙ 3 66,67,000 discard lower-order terms (e.g., = 000: million vs million),000 Leading-term approximation operation frequency tilde notation variable declaration + ~ assignment statement + ~ less than compare ½ ( + ) ( + ) ~ ½ equal to compare ½ ( ) ~ ½ Technical definition. f() ~ g() means lim f () g() = array access ( ) ~ increment ½ ( ) to ( ) ~ ½ to ~ Example: -SUM Example: 3-SUM Q. Approximately how many array accesses as a function of input size? Q. Approximately how many array accesses as a function of input size? for (int i = 0; i < ; i++) for (int j = i+; j < ; j++) if (a[i] + a[j] == 0) "inner loop" for (int i = 0; i < ; i++) for (int j = i+; j < ; j++) for (int k = j+; k < ; k++) if (a[i] + a[j] + a[k] == 0) "inner loop" A. ~ array accesses ( ) = ( ) = A. ~ ½ 3 array accesses. 3 = ( )( ) 3! 6 3 Bottom line. Use cost model and tilde notation to simplify counts. Bottom line. Use cost model and tilde notation to simplify counts
10 Diversion: estimating a discrete sum Estimating a discrete sum Q. How to estimate a discrete sum? A. Take a discrete mathematics course (COS 340). A. Replace the sum with an integral, and use calculus! Q. How to estimate a discrete sum? A. Take a discrete mathematics course (COS 340). A. Replace the sum with an integral, and use calculus! Ex Ex. k + k + + k. Ex 3. + / + /3 + + /. i= i= i= i i k i x= x= x= xdx x k dx dx = ln x k + k+ Ex 4. + ½ + ¼ + ⅛ + i=0 x=0 i = x dx = ln.447 Ex 4. 3-sum triple loop. i= j=i k=j x= y=x z=y dz dy dx 6 3 Caveat. Integral trick doesn't always work! Estimating a discrete sum Mathematical models for running time Q. How to estimate a discrete sum? A3. Use Maple or Wolfram Alpha. In principle, accurate mathematical models are available. In practice, Formulas can be complicated. Advanced mathematics might be required. Exact models best left for experts. costs (depend on machine, compiler) wolframalpha.com [wayne:nobel.princeton.edu] > maple5 \^/ Maple 5 (X86 64 LIUX)._ \ / _. Copyright (c) Maplesoft, a division of Waterloo Maple Inc. 0 \ MAPLE / All rights reserved. Maple is a trademark of < > Waterloo Maple Inc. Type? for help. > factor(sum(sum(sum(, k=j+..), j = i+..), i =..)); T = c A + c B + c3 C + c4 D + c5 E A = array access B = integer add C = integer compare D = increment E = variable assignment frequencies (depend on algorithm, input) ( - ) ( - ) Bottom line. We use approximate models in this course: T() ~ c
11 Analysis of algorithms quiz How many array accesses does the following code fragment make as a function of? A. ~ 3 B. ~ 3/ lg C. ~ 3/ 3 D. ~ 3 3 E. I don't know. for (int i = 0; i < ; i++) for (int j = i+; j < ; j++) for (int k = ; k < ; k = k*) if (a[i] + a[j] >= a[k]) Algorithms ROBERT SEDGEWICK KEVI WAYE AALYSIS OF ALGORITHMS introduction observations mathematical models order-of-growth classifications memory 4 Common order-of-growth classifications Common order-of-growth classifications Definition. If f () ~ c g() for some constant c > 0, then the order of growth of f () is g(). Ignores leading coefficient. Ignores lower-order terms. Ex. The order of growth of the running time of this code is 3. for (int i = 0; i < ; i++) for (int j = i+; j < ; j++) for (int k = j+; k < ; k++) if (a[i] + a[j] + a[k] == 0) Good news. The set of functions, log,, log,, 3, and suffices to describe the order of growth of most common algorithms. log-log plot time 5T 64T 8T 4T exponential cubic quadratic linearithmic linear Typical usage. With running times. where leading coefficient depends on machine, compiler, JVM, T T K logarithmic constant K 4K 8K 5K size Typical orders of growth 44
12 Common order-of-growth classifications Binary search order of growth name typical code framework description example T() / T() Goal. Given a sorted array and a key, find index of the key in the array? constant a = b + c; statement log logarithmic linear while ( > ) = /;... for (int i = 0; i < ; i++)... add two numbers divide in half binary search ~ loop find the maximum Binary search. Compare key against middle entry. Too small, go left. Too big, go right. Equal, found. log linearithmic [see mergesort lecture] divide and conquer mergesort ~ quadratic for (int i = 0; i < ; i++) for (int j = 0; j < ; j++)... double loop check all pairs cubic for (int i = 0; i < ; i++) for (int j = 0; j < ; j++) for (int k = 0; k < ; k++)... triple loop check all triples exponential [see combinatorial search lecture] exhaustive search check all subsets T() Binary search: implementation Binary search: Java implementation Trivial to implement? First binary search published in 946. First bug-free one in 96. Bug in Java's Arrays.binarySearch() discovered in 006. Invariant. If key appears in array a[], then a[lo] key a[hi]. public static int binarysearch(int[] a, int key) int lo = 0, hi = a.length - ; while (lo <= hi) why not mid = (lo + hi) /? int mid = lo + (hi - lo) / ; if (key < a[mid]) hi = mid - ; else if (key > a[mid]) lo = mid + ; else return mid; return -; one "3-way compare"
13 Binary search: mathematical analysis TECHICAL ITERVIEW QUESTIOS Proposition. Binary search uses at most + lg key compares to search in a sorted array of size. Def. T () = # key compares to binary search a sorted subarray of size. Binary search recurrence. T () T ( / ) + for >, with T () =. left or right half (floored division) Pf sketch. [assume is a power of ] possible to implement with one -way compare (instead of 3-way) T () T ( / ) + [ given ] T ( / 4) + + [ apply recurrence to first term ] T ( / 8) [ apply recurrence to first term ] T ( / ) [ stop applying, T() = ] = + lg lg WHY ARE MAHOLE COVERS ROUD? THE 3-SUM PROBLEM 3-SUM. Given distinct integers, find three such that a + b + c = 0. Version 0. 3 time, space. Version. log time, space. Version. time, space. ote. For full credit, running time should be worst case. ew York, ew York Geneva, Switzerland Zermatt, Switzerland 5 5
14 An log algorithm for 3-SUM Comparing programs Algorithm. Step : Sort the (distinct) numbers. Step : For each pair of numbers a[i] and a[j], binary search for -(a[i] + a[j]). input sort Hypothesis. The sorting-based log algorithm for 3-SUM is significantly faster in practice than the brute-force 3 algorithm. time (seconds) time (seconds) binary search,000 0., Analysis. Order of growth is log. Step : with insertion sort. Step : log with binary search. (-40, -0) 60 (-40, -0) 50 (-40, 0) 40 (-40, 5) 35 (-40, 0) 30, , , ThreeSum.java, , , , Remark. Can achieve by modifying binary search step. (-0, -0) 30 (-0, 0) 0 ( 0, 30) -40 ( 0, 40) -50 ( 30, 40) -70 only count if a[i] < a[j] < a[k] to avoid double counting 3, , ThreeSumDeluxe.java Guiding principle. Typically, better order of growth faster in practice Basics.4 AALYSIS OF ALGORITHMS Bit. 0 or. Byte. 8 bits. IST most computer scientists Megabyte (MB). million or 0 bytes. Gigabyte (GB). billion or 30 bytes. Algorithms ROBERT SEDGEWICK KEVI WAYE introduction observations mathematical models order-of-growth classifications memory 64-bit machine. We assume a 64-bit machine with 8-byte pointers. Can address more memory. some Pointers use more space. JVMs "compress" ordinary object pointers to 4 bytes to avoid this cost 56
15 Typical memory usage for primitive types and arrays Typical memory usage for objects in Java type bytes boolean byte char int 4 type bytes char[] + 4 int[] double[] one-dimensional arrays Object overhead. 6 bytes. Reference. 8 bytes. Padding. Each object uses a multiple of 8 bytes. Ex. A Date object uses 3 bytes of memory. float 4 long 8 double 8 primitive types type char[][] int[][] double[][] bytes ~ M ~ 4 M ~ 8 M public class Date private int day; private int month; private int year;... object overhead day month year padding int values 6 bytes (object overhead) 4 bytes (int) 4 bytes (int) 4 bytes (int) 4 bytes (padding) 3 bytes two-dimensional arrays Typical memory usage summary Memory analysis quiz Total memory usage for a data type value: Primitive type: 4 bytes for int, 8 bytes for double, Object reference: 8 bytes. Array: 4 bytes + memory for each array entry. Object: 6 bytes + memory for each instance variable. Padding: round up to multiple of 8 bytes. ote. Depending on application, we may want to count memory for any referenced objects (recursively). + 8 extra bytes per inner class object (for reference to enclosing class) How much memory does a WeightedQuickUnionUF use as a function of? A. ~ 4 bytes B. ~ 8 bytes C. ~ 4 bytes D. ~ 8 bytes E. I don't know public class WeightedQuickUnionUF private int[] id; private int[] sz; private int count; public WeightedQuickUnionUF(int ) id = new int[]; sz = new int[]; for (int i = 0; i < ; i++) id[i] = i; for (int i = 0; i < ; i++) sz[i] = ;
16 Turning the crank: summary Empirical analysis. Execute program to perform experiments. Assume power law and formulate a hypothesis for running time. Model enables us to make predictions. Mathematical analysis. Analyze algorithm to count frequency of operations. Use tilde notation to simplify analysis. Model enables us to explain behavior. Scientific method. Mathematical model is independent of a particular system; applies to machines not yet built. Empirical analysis is necessary to validate mathematical models and to make predictions. 6
Algorithms. 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 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 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 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 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 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 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 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 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 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 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 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 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 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 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 informationCS.7.A.Performance.Challenge
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
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 information8. 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 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 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 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 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 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 informationinput sort left half sort right half merge results Mergesort overview
Algorithms OBT S DGWICK K VIN W AYN Two classic sorting algorithms: mergesort and quicksort Critical components in the world s computational infrastructure. Full scientific understanding of their properties
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 informationLecture 2: Getting Started
Lecture 2: Getting Started Insertion Sort Our first algorithm is Insertion Sort Solves the sorting problem Input: A sequence of n numbers a 1, a 2,..., a n. Output: A permutation (reordering) a 1, a 2,...,
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 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 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 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 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 informationAlgorithms 1.5 UNION FIND. dynamic connectivity quick find quick union improvements applications
1.5 UNION FIND Algorithms F O U R T H E D I T I O N dynamic connectivity quick find quick union improvements applications R O B E R T S E D G E W I C K K E V I N W A Y N E Algorithms, 4 th Edition Robert
More informationAlgorithms 1.5 UNION FIND. dynamic connectivity quick find quick union improvements applications
1.5 UNION FIND Algorithms F O U R T H E D I T I O N dynamic connectivity quick find quick union improvements applications R O B E R T S E D G E W I C K K E V I N W A Y N E Algorithms, 4 th Edition Robert
More informationAlgorithms. Algorithms 1.5 UNION-FIND. dynamic connectivity quick find quick union improvements applications ROBERT SEDGEWICK KEVIN WAYNE
Algorithms ROBERT SEDGEWICK KEVIN WAYNE 1.5 UNION-FIND Algorithms F O U R T H E D I T I O N ROBERT SEDGEWICK KEVIN WAYNE dynamic connectivity quick find quick union improvements applications http://algs4.cs.princeton.edu
More informationAlgorithm Analysis. CENG 707 Data Structures and Algorithms
Algorithm Analysis CENG 707 Data Structures and Algorithms 1 Algorithm An algorithm is a set of instructions to be followed to solve a problem. There can be more than one solution (more than one algorithm)
More informationPrinciples of Algorithm Analysis. Biostatistics 615/815
Principles of Algorithm Analysis Biostatistics 615/815 Lecture 3 Snapshot of Incoming Class 25 Programming Languages 20 15 10 5 0 R C/C++ MatLab SAS Java Other Can you describe the QuickSort Algorithm?
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 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 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 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 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 informationSearching Algorithms/Time Analysis
Searching Algorithms/Time Analysis CSE21 Fall 2017, Day 8 Oct 16, 2017 https://sites.google.com/a/eng.ucsd.edu/cse21-fall-2017-miles-jones/ (MinSort) loop invariant induction Loop invariant: After the
More informationCS 112 Introduction to Computing II. Wayne Snyder Computer Science Department Boston University
CS 112 Introduction to Computing II Wayne Snyder Department Boston University Today Recursive Sorting Methods and their Complexity: Mergesort Conclusions on sorting algorithms and complexity Next Time:
More informationElementary Sorts. rules of the game selection sort insertion sort sorting challenges shellsort. Sorting problem. Ex. Student record in a University.
Sorting problem Ex. Student record in a University. Elementary Sorts rules of the game selection sort insertion sort sorting challenges shellsort Sort. Rearrange array of N objects into ascending order.
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 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 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 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 informationAlgorithms. Algorithms 2.2 MERGESORT. mergesort bottom-up mergesort sorting complexity comparators stability ROBERT SEDGEWICK KEVIN WAYNE
Algorithms ROBERT SEDGEWICK KEVIN WAYNE 2.2 MERGESORT Algorithms F O U R T H E D I T I O N ROBERT SEDGEWICK KEVIN WAYNE mergesort bottom-up mergesort sorting complexity comparators stability http://algs4.cs.princeton.edu
More informationAdvanced Algorithms and Data Structures
Advanced Algorithms and Data Structures Prof. Tapio Elomaa tapio.elomaa@tut.fi Course Prerequisites A seven credit unit course Replaced OHJ-2156 Analysis of Algorithms We take things a bit further than
More informationIntroduction to Asymptotic Running Time Analysis CMPSC 122
Introduction to Asymptotic Running Time Analysis CMPSC 122 I. Comparing Two Searching Algorithms Let's begin by considering two searching algorithms you know, both of which will have input parameters of
More informationThe divide-and-conquer paradigm involves three steps at each level of the recursion: Divide the problem into a number of subproblems.
2.3 Designing algorithms There are many ways to design algorithms. Insertion sort uses an incremental approach: having sorted the subarray A[1 j - 1], we insert the single element A[j] into its proper
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 informationSorting: Given a list A with n elements possessing a total order, return a list with the same elements in non-decreasing order.
Sorting The sorting problem is defined as follows: Sorting: Given a list A with n elements possessing a total order, return a list with the same elements in non-decreasing order. Remember that total order
More informationQuick Sort. Biostatistics 615 Lecture 9
Quick Sort Biostatistics 615 Lecture 9 Previously: Elementary Sorts Selection Sort Insertion Sort Bubble Sort Try to state an advantage for each one Selection Insertion Bubble Last Lecture: Shell Sort
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 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 informationCurriculum Map: Mathematics
Curriculum Map: Mathematics Course: Honors Advanced Precalculus and Trigonometry Grade(s): 11-12 Unit 1: Functions and Their Graphs This chapter will develop a more complete, thorough understanding of
More informationComputer Science Approach to problem solving
Computer Science Approach to problem solving If my boss / supervisor / teacher formulates a problem to be solved urgently, can I write a program to efficiently solve this problem??? Polynomial-Time Brute
More informationCOS 226 Algorithms and Data Structures Fall Midterm Solutions
1 COS 226 Algorithms and Data Structures Fall 2010 Midterm Solutions 1. Analysis of algorithms. (a) For each expression in the left column, give the best matching description from the right column. B.
More informationRecursion & Performance. Recursion. Recursion. Recursion. Where Recursion Shines. Breaking a Problem Down
Recursion & Performance Recursion Part 7 The best way to learn recursion is to, first, learn recursion! Recursion Recursion Recursion occurs when a function directly or indirectly calls itself This results
More informationSorting. There exist sorting algorithms which have shown to be more efficient in practice.
Sorting Next to storing and retrieving data, sorting of data is one of the more common algorithmic tasks, with many different ways to perform it. Whenever we perform a web search and/or view statistics
More informationFull file at
Java Programming: From Problem Analysis to Program Design, 3 rd Edition 2-1 Chapter 2 Basic Elements of Java At a Glance Instructor s Manual Table of Contents Overview Objectives s Quick Quizzes Class
More informationComputer Science 1 Ah
UNIVERSITY OF EDINBURGH course CS0077 COLLEGE OF SCIENCE AND ENGINEERING SCHOOL OF INFORMATICS Computer Science 1 Ah Resit Examination Specimen Solutions Date: Monday 1st September 2003 Time: 09:30 11:00
More informationCloning Arrays. In practice, one might duplicate an array for some reason. One could attempt to use the assignment statement (=), for example,
Cloning Arrays In practice, one might duplicate an array for some reason. One could attempt to use the assignment statement (=), for example, 1... 2 T[] A = {...}; // assume A is an array 3 T[] B = A;
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 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 informationElementary Sorts. ! rules of the game! selection sort! insertion sort! sorting challenges! shellsort. Sorting problem
Sorting problem Ex. Student record in a University. Elementary Sorts rules of the game selection sort insertion sort sorting challenges shellsort Sort. Rearrange array of N objects into ascending order.
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 informationSorting is a problem for which we can prove a non-trivial lower bound.
Sorting The sorting problem is defined as follows: Sorting: Given a list a with n elements possessing a total order, return a list with the same elements in non-decreasing order. Remember that total order
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 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 information4.2 Sorting and Searching. Section 4.2
. Sorting and Searching Section. Searching The problem: Given a collection of data, determine if a query is contained in that collection. This is a fundamentally important problem for a myriad of applications
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 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 informationAlgorithms. Algorithms GEOMETRIC APPLICATIONS OF BSTS. 1d range search line segment intersection kd trees interval search trees rectangle intersection
Algorithms ROBERT SEDGEWICK KEVIN WAYNE GEOMETRIC APPLICATIONS OF BSTS Algorithms F O U R T H E D I T I O N ROBERT SEDGEWICK KEVIN WAYNE 1d range search line segment intersection kd trees interval search
More informationAlgorithms. Algorithms GEOMETRIC APPLICATIONS OF BSTS. 1d range search line segment intersection kd trees interval search trees rectangle intersection
Algorithms ROBERT SEDGEWICK KEVIN WAYNE GEOMETRIC APPLICATIONS OF BSTS Algorithms F O U R T H E D I T I O N ROBERT SEDGEWICK KEVIN WAYNE 1d range search line segment intersection kd trees interval search
More information7 Fractions. Number Sense and Numeration Measurement Geometry and Spatial Sense Patterning and Algebra Data Management and Probability
7 Fractions GRADE 7 FRACTIONS continue to develop proficiency by using fractions in mental strategies and in selecting and justifying use; develop proficiency in adding and subtracting simple fractions;
More informationBinary floating point encodings
Week 1: Wednesday, Jan 25 Binary floating point encodings Binary floating point arithmetic is essentially scientific notation. Where in decimal scientific notation we write in floating point, we write
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 informationAlgorithms. Algorithms GEOMETRIC APPLICATIONS OF BSTS. 1d range search line segment intersection kd trees interval search trees rectangle intersection
Algorithms ROBERT SEDGEWICK KEVIN WAYNE GEOMETRIC APPLICATIONS OF BSTS Algorithms F O U R T H E D I T I O N ROBERT SEDGEWICK KEVIN WAYNE 1d range search line segment intersection kd trees interval search
More informationCSE373: Data Structures and Algorithms Lecture 4: Asymptotic Analysis. Aaron Bauer Winter 2014
CSE373: Data Structures and Algorithms Lecture 4: Asymptotic Analysis Aaron Bauer Winter 2014 Previously, on CSE 373 We want to analyze algorithms for efficiency (in time and space) And do so generally
More informationWhat did we talk about last time? Examples switch statements
Week 4 - Friday What did we talk about last time? Examples switch statements History of computers Hardware Software development Basic Java syntax Output with System.out.print() Mechanical Calculation
More informationSum this up for me. Let s write a method to calculate the sum from 1 to some n. Gauss also has a way of solving this. Which one is more efficient?
Sum this up for me Let s write a method to calculate the sum from 1 to some n public static int sum1(int n) { int sum = 0; for (int i = 1; i
More informationAlgorithms. Algorithms 2.2 MERGESORT. mergesort bottom-up mergesort sorting complexity comparators stability ROBERT SEDGEWICK KEVIN WAYNE
Algorithms ROBERT SEDGEWICK KEVIN WAYNE 2.2 MERGESORT Algorithms F O U R T H E D I T I O N ROBERT SEDGEWICK KEVIN WAYNE mergesort bottom-up mergesort sorting complexity comparators stability http://algs4.cs.princeton.edu
More information17/05/2018. Outline. Outline. Divide and Conquer. Control Abstraction for Divide &Conquer. Outline. Module 2: Divide and Conquer
Module 2: Divide and Conquer Divide and Conquer Control Abstraction for Divide &Conquer 1 Recurrence equation for Divide and Conquer: If the size of problem p is n and the sizes of the k sub problems are
More informationBits, Words, and Integers
Computer Science 52 Bits, Words, and Integers Spring Semester, 2017 In this document, we look at how bits are organized into meaningful data. In particular, we will see the details of how integers are
More informationAlgorithms + Data Structures Programs
Introduction Algorithms Method for solving problems suitable for computer implementation Generally independent of computer hardware characteristics Possibly suitable for many different programming languages
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 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 information! Widely available. ! Widely used. ! Variety of automatic checks for mistakes in programs. ! Embraces full set of modern abstractions. Caveat.
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. Caveat.! No perfect
More informationRun Times. Efficiency Issues. Run Times cont d. More on O( ) notation
Comp2711 S1 2006 Correctness Oheads 1 Efficiency Issues Comp2711 S1 2006 Correctness Oheads 2 Run Times An implementation may be correct with respect to the Specification Pre- and Post-condition, but nevertheless
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 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 information6. Asymptotics: The Big-O and Other Notations
Chapter 7 SEARCHING 1. Introduction, Notation 2. Sequential Search 3. Binary Search 4. Comparison Trees 5. Lower Bounds 6. Asymptotics: The Big-O and Other Notations Outline Transp. 1, Chapter 7, Searching
More informationAlgorithms. Algorithms 1.5 UNION FIND. union find data type quick-find quick-union improvements applications ROBERT SEDGEWICK KEVIN WAYNE
Algorithms ROBERT SEDGEWICK KEVIN WAYNE 1.5 UNION FIND Algorithms F O U R T H E D I T I O N ROBERT SEDGEWICK KEVIN WAYNE union find data type quick-find quick-union improvements applications http://algs4.cs.princeton.edu
More information