Fundamentals of Python: From First Programs Through Data Structures

Slides:



Advertisements
Similar presentations
Growth-rate Functions
Advertisements

MATH 224 – Discrete Mathematics
CHAPTER 2 ALGORITHM ANALYSIS 【 Definition 】 An algorithm is a finite set of instructions that, if followed, accomplishes a particular task. In addition,
Copyright © 2014, 2008 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Starting Out with C++ Early Objects Eighth Edition by Tony Gaddis,
HST 952 Computing for Biomedical Scientists Lecture 10.
Razdan with contribution from others 1 Algorithm Analysis What is the Big ‘O Bout? Anshuman Razdan Div of Computing.
Computer Science 101 Efficiency and Complexity Analysis.
ALG0183 Algorithms & Data Structures Lecture 3 Algorithm Analysis 8/25/20091 ALG0183 Algorithms & Data Structures by Dr Andy Brooks Weiss Chapter 5 Sahni.
Chapter 9: Searching, Sorting, and Algorithm Analysis
Computational Complexity 1. Time Complexity 2. Space Complexity.
1 Chapter 4 Analysis Tools. 2 Which is faster – selection sort or insertion sort? Potential method for evaluation: Implement each as a method and then.
Algorithmic Complexity Nelson Padua-Perez Bill Pugh Department of Computer Science University of Maryland, College Park.
Fall 2006CENG 7071 Algorithm Analysis. Fall 2006CENG 7072 Algorithmic Performance There are two aspects of algorithmic performance: Time Instructions.
Introduction to Analysis of Algorithms
© 2006 Pearson Addison-Wesley. All rights reserved10-1 Chapter 10 Algorithm Efficiency and Sorting CS102 Sections 51 and 52 Marc Smith and Jim Ten Eyck.
Scott Grissom, copyright 2004 Chapter 5 Slide 1 Analysis of Algorithms (Ch 5) Chapter 5 focuses on: algorithm analysis searching algorithms sorting algorithms.
Complexity Analysis (Part I)
CS107 Introduction to Computer Science
Cmpt-225 Algorithm Efficiency.
Concept of Basic Time Complexity Problem size (Input size) Time complexity analysis.
Algorithm Efficiency and Sorting Bina Ramamurthy CSE116A,B.
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved Chapter 23 Algorithm Efficiency.
Analysis of Algorithms 7/2/2015CS202 - Fundamentals of Computer Science II1.
CS107 Introduction to Computer Science Lecture 7, 8 An Introduction to Algorithms: Efficiency of algorithms.
Analysis of Algorithms COMP171 Fall Analysis of Algorithms / Slide 2 Introduction * What is Algorithm? n a clearly specified set of simple instructions.
© 2006 Pearson Addison-Wesley. All rights reserved10 A-1 Chapter 10 Algorithm Efficiency and Sorting.
Analysis of Algorithms Spring 2015CS202 - Fundamentals of Computer Science II1.
Algorithm Analysis (Big O)
1 Complexity Lecture Ref. Handout p
Liang, Introduction to Java Programming, Seventh Edition, (c) 2009 Pearson Education, Inc. All rights reserved Chapter 23 Algorithm Efficiency.
Discrete Mathematics Algorithms. Introduction  An algorithm is a finite set of instructions with the following characteristics:  Precision: steps are.
1 Chapter 24 Developing Efficient Algorithms. 2 Executing Time Suppose two algorithms perform the same task such as search (linear search vs. binary search)
1 Recursion Algorithm Analysis Standard Algorithms Chapter 7.
Analysis Tools Jyh-Shing Roger Jang ( 張智星 ) CSIE Dept, National Taiwan University.
Chapter 12 Recursion, Complexity, and Searching and Sorting
Analysis of Algorithms
Chapter 19: Searching and Sorting Algorithms
Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley. Ver Chapter 9: Algorithm Efficiency and Sorting Data Abstraction &
Chapter 3 Sec 3.3 With Question/Answer Animations 1.
© 2011 Pearson Addison-Wesley. All rights reserved 10 A-1 Chapter 10 Algorithm Efficiency and Sorting.
Chapter 10 A Algorithm Efficiency. © 2004 Pearson Addison-Wesley. All rights reserved 10 A-2 Determining the Efficiency of Algorithms Analysis of algorithms.
Analysis of Algorithms CSCI Previous Evaluations of Programs Correctness – does the algorithm do what it is supposed to do? Generality – does it.
Starting Out with C++ Early Objects Seventh Edition by Tony Gaddis, Judy Walters, and Godfrey Muganda Modified for use by MSU Dept. of Computer Science.
Chapter 18: Searching and Sorting Algorithms. Objectives In this chapter, you will: Learn the various search algorithms Implement sequential and binary.
Java Methods Big-O Analysis of Algorithms Object-Oriented Programming
Algorithm Analysis Part of slides are borrowed from UST.
1 Algorithms  Algorithms are simply a list of steps required to solve some particular problem  They are designed as abstractions of processes carried.
Computer Science 112 Fundamentals of Programming II Searching, Sorting, and Complexity Analysis.
E.G.M. PetrakisAlgorithm Analysis1  Algorithms that are equally correct can vary in their utilization of computational resources  time and memory  a.
Searching Topics Sequential Search Binary Search.
1 Chapter 2 Program Performance. 2 Concepts Memory and time complexity of a program Measuring the time complexity using the operation count and step count.
Copyright © 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Starting Out with C++ Early Objects Seventh Edition by Tony Gaddis, Judy.
Analysis of Algorithms Spring 2016CS202 - Fundamentals of Computer Science II1.
GC 211:Data Structures Week 2: Algorithm Analysis Tools Slides are borrowed from Mr. Mohammad Alqahtani.
Chapter 15 Running Time Analysis. Topics Orders of Magnitude and Big-Oh Notation Running Time Analysis of Algorithms –Counting Statements –Evaluating.
1 Algorithms Searching and Sorting Algorithm Efficiency.
Algorithm Complexity is concerned about how fast or slow particular algorithm performs.
Data Structures I (CPCS-204) Week # 2: Algorithm Analysis tools Dr. Omar Batarfi Dr. Yahya Dahab Dr. Imtiaz Khan.
Algorithm Analysis 1.
Analysis of Algorithms
Introduction to Search Algorithms
Computer Science 112 Fundamentals of Programming II
Algorithm design and Analysis
Chapter 12: Analysis of Algorithms
Algorithm An algorithm is a finite set of steps required to solve a problem. An algorithm must have following properties: Input: An algorithm must have.
Analysis of Algorithms
Fundamentals of Python: First Programs Second Edition
Analysis of Algorithms
Presentation transcript:

Fundamentals of Python: From First Programs Through Data Structures Chapter 11 Searching, Sorting, and Complexity Analysis

Objectives After completing this chapter, you will be able to: Measure the performance of an algorithm by obtaining running times and instruction counts with different data sets Analyze an algorithm’s performance by determining its order of complexity, using big-O notation Fundamentals of Python: From First Programs Through Data Structures

Objectives (continued) Distinguish the common orders of complexity and the algorithmic patterns that exhibit them Distinguish between the improvements obtained by tweaking an algorithm and reducing its order of complexity Write a simple linear search algorithm and a simple sort algorithm Fundamentals of Python: From First Programs Through Data Structures

Measuring the Efficiency of Algorithms When choosing algorithms, we often have to settle for a space/time tradeoff An algorithm can be designed to gain faster run times at the cost of using extra space (memory), or the other way around Memory is now quite inexpensive for desktop and laptop computers, but not yet for miniature devices Fundamentals of Python: From First Programs Through Data Structures

Measuring the Run Time of an Algorithm One way to measure the time cost of an algorithm is to use computer’s clock to obtain actual run time Benchmarking or profiling Can use time() in time module Returns number of seconds that have elapsed between current time on the computer’s clock and January 1, 1970 Fundamentals of Python: From First Programs Through Data Structures

Measuring the Run Time of an Algorithm (continued) Fundamentals of Python: From First Programs Through Data Structures

Measuring the Run Time of an Algorithm (continued) Fundamentals of Python: From First Programs Through Data Structures

Measuring the Run Time of an Algorithm (continued) Fundamentals of Python: From First Programs Through Data Structures

Measuring the Run Time of an Algorithm (continued) This method permits accurate predictions of the running times of many algorithms Problems: Different hardware platforms have different processing speeds, so the running times of an algorithm differ from machine to machine Running time varies with OS and programming language too It is impractical to determine the running time for some algorithms with very large data sets Fundamentals of Python: From First Programs Through Data Structures

Counting Instructions Another technique is to count the instructions executed with different problem sizes We count the instructions in the high-level code in which the algorithm is written, not instructions in the executable machine language program Distinguish between: Instructions that execute the same number of times regardless of problem size For now, we ignore instructions in this class Instructions whose execution count varies with problem size Fundamentals of Python: From First Programs Through Data Structures

Counting Instructions (continued) Fundamentals of Python: From First Programs Through Data Structures

Counting Instructions (continued) Fundamentals of Python: From First Programs Through Data Structures

Counting Instructions (continued) Fundamentals of Python: From First Programs Through Data Structures

Counting Instructions (continued) Fundamentals of Python: From First Programs Through Data Structures

Measuring the Memory Used by an Algorithm A complete analysis of the resources used by an algorithm includes the amount of memory required We focus on rates of potential growth Some algorithms require the same amount of memory to solve any problem Other algorithms require more memory as the problem size gets larger Fundamentals of Python: From First Programs Through Data Structures

Complexity Analysis Complexity analysis entails reading the algorithm and using pencil and paper to work out some simple algebra Used to determine efficiency of algorithms Allows us to rate them independently of platform-dependent timings or impractical instruction counts Fundamentals of Python: From First Programs Through Data Structures

Orders of Complexity Consider the two counting loops discussed earlier: When we say “work,” we usually mean the number of iterations of the most deeply nested loop Fundamentals of Python: From First Programs Through Data Structures

Orders of Complexity (continued) The performances of these algorithms differ by what we call an order of complexity The first algorithm is linear The second algorithm is quadratic Fundamentals of Python: From First Programs Through Data Structures

Orders of Complexity (continued) Fundamentals of Python: From First Programs Through Data Structures

Big-O Notation The amount of work in an algorithm typically is the sum of several terms in a polynomial We focus on one term as dominant As n becomes large, the dominant term becomes so large that the amount of work represented by the other terms can be ignored Asymptotic analysis Big-O notation: used to express the efficiency or computational complexity of an algorithm Fundamentals of Python: From First Programs Through Data Structures

The Role of the Constant of Proportionality The constant of proportionality involves the terms and coefficients that are usually ignored during big-O analysis However, when these items are large, they may have an impact on the algorithm, particularly for small and medium-sized data sets The amount of abstract work performed by the following algorithm is 3n + 1 Fundamentals of Python: From First Programs Through Data Structures

Search Algorithms We now present several algorithms that can be used for searching and sorting lists We first discuss the design of an algorithm, We then show its implementation as a Python function, and, Finally, we provide an analysis of the algorithm’s computational complexity To keep things simple, each function processes a list of integers Fundamentals of Python: From First Programs Through Data Structures

Search for a Minimum Python’s min function returns the minimum or smallest item in a list Alternative version: n – 1 comparisons for a list of size n O(n) Fundamentals of Python: From First Programs Through Data Structures

Linear Search of a List Python’s in operator is implemented as a method named __contains__ in the list class Uses a sequential search or a linear search Python code for a linear search function: Analysis is different from previous one Fundamentals of Python: From First Programs Through Data Structures

Best-Case, Worst-Case, and Average-Case Performance Analysis of a linear search considers three cases: In the worst case, the target item is at the end of the list or not in the list at all O(n) In the best case, the algorithm finds the target at the first position, after making one iteration O(1) Average case: add number of iterations required to find target at each possible position; divide sum by n Fundamentals of Python: From First Programs Through Data Structures

Binary Search of a List A linear search is necessary for data that are not arranged in any particular order When searching sorted data, use a binary search Fundamentals of Python: From First Programs Through Data Structures

Binary Search of a List (continued) More efficient than linear search Additional cost has to do with keeping list in order Fundamentals of Python: From First Programs Through Data Structures

Comparing Data Items and the cmp Function To allow algorithms to use comparison operators with a new class of objects, define __cmp__ Header: def __cmp__(self, other): Should return: 0 when the two objects are equal A number less than 0 if self < other A number greater than 0 if self > other Fundamentals of Python: From First Programs Through Data Structures

Comparing Data Items and the cmp Function (continued) Fundamentals of Python: From First Programs Through Data Structures

Comparing Data Items and the cmp Function (continued) Fundamentals of Python: From First Programs Through Data Structures

Sort Algorithms The sort functions that we develop here operate on a list of integers and uses a swap function to exchange the positions of two items in the list Fundamentals of Python: From First Programs Through Data Structures

Selection Sort Perhaps the simplest strategy is to search the entire list for the position of the smallest item If that position does not equal the first position, the algorithm swaps the items at those positions Fundamentals of Python: From First Programs Through Data Structures

Selection Sort (continued) Selection sort is O(n2) in all cases For large data sets, the cost of swapping items might also be significant This additional cost is linear in worst/average cases Fundamentals of Python: From First Programs Through Data Structures

Bubble Sort Starts at beginning of list and compares pairs of data items as it moves down to the end When items in pair are out of order, swap them Fundamentals of Python: From First Programs Through Data Structures

Bubble Sort (continued) Bubble sort is O(n2) Will not perform any swaps if list is already sorted Worst-case behavior for exchanges is greater than linear Can be improved, but average case is still O(n2) Fundamentals of Python: From First Programs Through Data Structures

Insertion Sort Worst-case behavior of insertion sort is O(n2) Fundamentals of Python: From First Programs Through Data Structures

Insertion Sort (continued) The more items in the list that are in order, the better insertion sort gets until, in the best case of a sorted list, the sort’s behavior is linear In the average case, insertion sort is still quadratic Fundamentals of Python: From First Programs Through Data Structures

Best-Case, Worst-Case, and Average-Case Performance Revisited Thorough analysis of an algorithm’s complexity divides its behavior into three types of cases: Best case Worst case Average case There are algorithms whose best-case and average-case performances are similar, but whose performance can degrade to a worst case When choosing/developing an algorithm, it is important to be aware of these distinctions Fundamentals of Python: From First Programs Through Data Structures

An Exponential Algorithm: Recursive Fibonacci Fundamentals of Python: From First Programs Through Data Structures

An Exponential Algorithm: Recursive Fibonacci (continued) Exponential algorithms are generally impractical to run with any but very small problem sizes Recursive functions that are called repeatedly with same arguments can be made more efficient by technique called memoization Program maintains a table of the values for each argument used with the function Before the function recursively computes a value for a given argument, it checks the table to see if that argument already has a value Fundamentals of Python: From First Programs Through Data Structures

Converting Fibonacci to a Linear Algorithm Pseudocode: Set sum to 1 Set first to 1 Set second to 1 Set count to 3 While count <= N Set sum to first + second Set first to second Set second to sum Increment count Fundamentals of Python: From First Programs Through Data Structures

Converting Fibonacci to a Linear Algorithm (continued) Fundamentals of Python: From First Programs Through Data Structures

Case Study: An Algorithm Profiler Profiling: measuring an algorithm’s performance, by counting instructions and/or timing execution Request: Write a program to allow profiling of sort algorithms Analysis: Configure a sort algorithm to be profiled as follows: Define sort function to receive a Profiler as a 2nd parameter In algorithm’s code, run comparison() and exchange() with the Profiler object where relevant, to count comparisons and exchanges Fundamentals of Python: From First Programs Through Data Structures

Case Study: An Algorithm Profiler (continued) Fundamentals of Python: From First Programs Through Data Structures

Case Study: An Algorithm Profiler (continued) Design: Two modules: profiler—defines the Profiler class algorithms—defines the sort functions, as configured for profiling Implementation (Coding): Next slide shows a partial implementation of the algorithms module Fundamentals of Python: From First Programs Through Data Structures

Case Study: An Algorithm Profiler (continued) Fundamentals of Python: From First Programs Through Data Structures

Summary Different algorithms can be ranked according to time and memory resources that they require Running time of an algorithm can be measured empirically using computer’s clock Counting instructions provides measurement of amount of work that algorithm does Rate of growth of algorithm’s work can be expressed as a function of the size of its problem instances Big-O notation is a common way of expressing an algorithm’s runtime behavior Fundamentals of Python: From First Programs Through Data Structures

Summary (continued) Common expressions of run-time behavior are O(log2n), O(n), O(n2), and O(kn) An algorithm can have different best-case, worst-case, and average-case behaviors In general, it is better to try to reduce the order of an algorithm’s complexity than it is to try to enhance performance by tweaking the code Binary search is faster than linear search (but data must be ordered) Exponential algorithms are impractical to run with large problem sizes Fundamentals of Python: From First Programs Through Data Structures