Chapter 12 Recursion, Complexity, and Searching and Sorting

Slides:



Advertisements
Similar presentations
Introduction to Algorithms Quicksort
Advertisements

Chapter 13 Recursion, Complexity, and Searching and Sorting
MATH 224 – Discrete Mathematics
Algorithms Analysis Lecture 6 Quicksort. Quick Sort Divide and Conquer.
Chapter 3: The Efficiency of Algorithms Invitation to Computer Science, Java Version, Third Edition.
Fundamentals of Python: From First Programs Through Data Structures
ISOM MIS 215 Module 7 – Sorting. ISOM Where are we? 2 Intro to Java, Course Java lang. basics Arrays Introduction NewbieProgrammersDevelopersProfessionalsDesigners.
Sorting Chapter Sorting Consider list x 1, x 2, x 3, … x n We seek to arrange the elements of the list in order –Ascending or descending Some O(n.
Recursion. Binary search example postponed to end of lecture.
Recursion Chapter 11 Chapter 11.
© 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.
Chapter 10 Recursion. Copyright © 2005 Pearson Addison-Wesley. All rights reserved Chapter Objectives Explain the underlying concepts of recursion.
Recursion.
Chapter 3: The Efficiency of Algorithms Invitation to Computer Science, C++ Version, Fourth Edition.
Chapter 3: The Efficiency of Algorithms
Elementary Data Structures and Algorithms
CHAPTER 10 Recursion. 2 Recursive Thinking Recursion is a programming technique in which a method can call itself to solve a problem A recursive definition.
© 2006 Pearson Addison-Wesley. All rights reserved10 A-1 Chapter 10 Algorithm Efficiency and Sorting.
 2006 Pearson Education, Inc. All rights reserved Searching and Sorting.
HOW TO SOLVE IT? Algorithms. An Algorithm An algorithm is any well-defined (computational) procedure that takes some value, or set of values, as input.
Liang, Introduction to Java Programming, Seventh Edition, (c) 2009 Pearson Education, Inc. All rights reserved Chapter 23 Algorithm Efficiency.
Nyhoff, ADTs, Data Structures and Problem Solving with C++, Second Edition, © 2005 Pearson Education, Inc. All rights reserved ADT Implementation:
Recursion, Complexity, and Searching and Sorting By Andrew Zeng.
1 Chapter 24 Developing Efficient Algorithms. 2 Executing Time Suppose two algorithms perform the same task such as search (linear search vs. binary search)
JAVA: An Introduction to Problem Solving & Programming, 5 th Ed. By Walter Savitch and Frank Carrano. ISBN © 2008 Pearson Education, Inc., Upper.
1 Recursion Algorithm Analysis Standard Algorithms Chapter 7.
Comp 249 Programming Methodology Chapter 10 – Recursion Prof. Aiman Hanna Department of Computer Science & Software Engineering Concordia University, Montreal,
1 Time Analysis Analyzing an algorithm = estimating the resources it requires. Time How long will it take to execute? Impossible to find exact value Depends.
Data Structures and Abstractions with Java, 4e Frank Carrano
Recursion, Complexity, and Sorting By Andrew Zeng.
Recursion Chapter 11. The Basics of Recursion: Outline Introduction to Recursion How Recursion Works Recursion versus Iteration Recursive Methods That.
Analysis of Algorithms
Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley. Ver Chapter 9: Algorithm Efficiency and Sorting Data Abstraction &
Merge Sort. What Is Sorting? To arrange a collection of items in some specified order. Numerical order Lexicographical order Input: sequence of numbers.
Chapter 13 Recursion. Learning Objectives Recursive void Functions – Tracing recursive calls – Infinite recursion, overflows Recursive Functions that.
 2005 Pearson Education, Inc. All rights reserved Searching and Sorting.
 Pearson Education, Inc. All rights reserved Searching and Sorting.
C++ Programming: From Problem Analysis to Program Design, Second Edition Chapter 19: Searching and Sorting.
CSC 221: Recursion. Recursion: Definition Function that solves a problem by relying on itself to compute the correct solution for a smaller version of.
Data Structures R e c u r s i o n. Recursive Thinking Recursion is a problem-solving approach that can be used to generate simple solutions to certain.
Java Programming: Guided Learning with Early Objects Chapter 11 Recursion.
Sorting Chapter Sorting Consider list x 1, x 2, x 3, … x n We seek to arrange the elements of the list in order –Ascending or descending Some O(n.
Chapter 12 Binary Search and QuickSort Fundamentals of Java.
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
Review 1 Selection Sort Selection Sort Algorithm Time Complexity Best case Average case Worst case Examples.
Searching Topics Sequential Search Binary Search.
Chapter 111 Recursion Chapter Objectives become familiar with the idea of recursion learn to use recursion as a programming tool become familiar.
Quick Sort Modifications By Mr. Dave Clausen Updated for Python.
Chapter 9 Recursion © 2006 Pearson Education Inc., Upper Saddle River, NJ. All rights reserved.
Chapter 15: Recursion. Recursive Definitions Recursion: solving a problem by reducing it to smaller versions of itself – Provides a powerful way to solve.
JAVA: An Introduction to Problem Solving & Programming, 7 th Ed. By Walter Savitch ISBN © 2015 Pearson Education, Inc., Upper Saddle River,
WHICH SEARCH OR SORT IS BETTER?. COMPARING ALGORITHMS Time efficiency refers to how long it takes an algorithm to run Space efficiency refers to the amount.
1 Algorithms Searching and Sorting Algorithm Efficiency.
Nyhoff, ADTs, Data Structures and Problem Solving with C++, Second Edition, © 2005 Pearson Education, Inc. All rights reserved Recursion,
Sorts, CompareTo Method and Strings
19 Searching and Sorting.
Recursion DRILL: Please take out your notes on Recursion
Searching – Linear and Binary Searches
Introduction to complexity
Chapter 8: Recursion Java Software Solutions
Teach A level Computing: Algorithms and Data Structures
Algorithm design and Analysis
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.
Chapter 8: Recursion Java Software Solutions
Chapter 3: The Efficiency of Algorithms
Chapter 8: Recursion Java Software Solutions
Presentation transcript:

Chapter 12 Recursion, Complexity, and Searching and Sorting Fundamentals of Java

Objectives Design and implement a recursive method to solve a problem. Understand the similarities and differences between recursive and iterative solutions of a problem. Check and test a recursive method for correctness. Fundamentals of Java

Objectives (cont.) Understand how a computer executes a recursive method. Perform a simple complexity analysis of an algorithm using big-O notation. Recognize some typical orders of complexity. Understand the behavior of a complex sort algorithm, such as the quicksort. Fundamentals of Java

Vocabulary Activation record Big-O notation Binary search algorithm Call stack Complexity analysis Fundamentals of Java

Vocabulary (cont.) Infinite recursion Iterative process Merge sort Quicksort Recursive method Fundamentals of Java

Vocabulary (cont.) Recursive step Stack Stack overflow error Stopping state Tail-recursive Fundamentals of Java

Recursion Recursive functions are defined in terms of themselves. sum(n) = n + sum(n-1) if n > 1 Example: Other functions that could be defined recursively include factorial and Fibonacci sequence. Fundamentals of Java

Recursion (cont.) A method is recursive if it calls itself. Factorial example: Fibonacci sequence example: Fundamentals of Java

Recursion (cont.) Tracing a recursive method can help to understand it: Fundamentals of Java

Recursion (cont.) Guidelines for implementing recursive methods: Must have a well-defined stopping state The recursive step must lead to the stopping state. The step in which the method calls itself If either condition is not met, it will result in infinite recursion. Creates a stack overflow error and program crashes Fundamentals of Java

Recursion (cont.) Run-time support for recursive methods: A call stack (large storage area) is created at program startup. When a method is called, an activation record is added to the top of the call stack. Contains space for the method parameters, the method’s local variables, and the return value When a method returns, its activation record is removed from the top of the stack. Fundamentals of Java

Recursion (cont.) Figure 12-1: Activation records on the call stack during recursive calls to factorial Fundamentals of Java

Recursion (cont.) Figure 12-2: Activation records on the call stack during returns from recursive calls to factorial Fundamentals of Java

Recursion (cont.) Recursion can always be used in place of iteration, and vice-versa. Executing a method call and the corresponding return statement usually takes longer than incrementing and testing a loop control variable. Method calls tie up memory that is not freed until the methods complete their tasks. However, recursion can be much more elegant than iteration. Fundamentals of Java

Recursion (cont.) Tail-recursive algorithms perform no work after the recursive call. Some compilers can optimize the compiled code so that no extra stack memory is required. Fundamentals of Java

Complexity Analysis What is the effect on the method of increasing the quantity of data processed? Does execution time increase exponentially or linearly with amount of data being processed? Example: Fundamentals of Java

Complexity Analysis (cont.) If array’s size is n, the execution time is determined as follows: Execution time can be expressed using Big-O notation. Previous example is O(n) Execution time is on the order of n. Linear time Fundamentals of Java

Complexity Analysis (cont.) Another O(n) method: Fundamentals of Java

Complexity Analysis (cont.) An O(n2) method: Fundamentals of Java

Complexity Analysis (cont.) Table 12-1: Names of some common big-O values Fundamentals of Java

Complexity Analysis (cont.) O(1) is best complexity. Exponential complexity is generally bad. Table 12-2: How big-O values vary depending on n Fundamentals of Java

Complexity Analysis (cont.) Recursive Fibonacci sequence algorithm is exponential. O(rn), where r ≈ 1.62 Figure 12-7: Calls needed to compute the sixth Fibonacci number recursively Fundamentals of Java

Complexity Analysis (cont.) Table 12-3: Calls needed to compute the nth Fibonacci number recursively Fundamentals of Java

Complexity Analysis (cont.) Three cases of complexity are typically analyzed for an algorithm: Best case: When does an algorithm do the least work, and with what complexity? Worst case: When does an algorithm do the most work, and with what complexity? Average case: When does an algorithm do a typical amount of work, and with what complexity? Fundamentals of Java

Complexity Analysis (cont.) Examples: A summation of array values has a best, worst, and typical complexity of O(n). Always visits every array element A linear search: Best case of O(1) – element found on first iteration Worst case of O(n) – element found on last iteration Average case of O(n/2) Fundamentals of Java

Complexity Analysis (cont.) Bubble sort complexity: Best case is O(n) – when array already sorted Worst case is O(n2) – array sorted in reverse order Average case is closer to O(n2). Fundamentals of Java

Figure 12-8: Binary search algorithm (searching for 320) Figure 12-9: List for the binary search algorithm with all numbers visible Fundamentals of Java

Binary Search (cont.) Table 12-4: Maximum number of steps needed to binary search lists of various sizes Fundamentals of Java

Binary Search (cont.) Iterative and recursive binary searches are O(log n). Fundamentals of Java

Figure 12-10: Steps in an iterative binary search for the number 320 Binary Search (cont.) Figure 12-10: Steps in an iterative binary search for the number 320 Fundamentals of Java

Binary Search (cont.) Fundamentals of Java

Quicksort Sorting algorithms, such as insertion sort and bubble sort, are O(n2). Quick Sort is O(n log n). Break array into two parts and then move larger values to one end and smaller values to other end. Recursively repeat procedure on each array half. Fundamentals of Java

Figure 12-11: An unsorted array Quicksort (cont.) Figure 12-11: An unsorted array Phase 1: Fundamentals of Java

Quicksort (cont.) Phase 1 (cont.): Fundamentals of Java

Quicksort (cont.) Phase 1 (cont.): Fundamentals of Java

Quicksort (cont.) Phase 1 (cont.): Fundamentals of Java

Quicksort (cont.) Phase 1 (cont.): Fundamentals of Java

Quicksort (cont.) Phase 1 (cont.): Phase 2 and beyond: Recursively perform phase 1 on each half of the array. Fundamentals of Java

Quicksort (cont.) Complexity analysis: Amount of work in phase 1 is O(n). Amount of work in phase 2 and beyond is O(n). In the typical case, there will be log2 n phases. Overall complexity will be O(n log2 n). Fundamentals of Java

Quicksort (cont.) Implementation: Fundamentals of Java

Merge Sort Recursive, divide-and-conquer approach Compute middle position of an array and recursively sort left and right subarrays. Merge sorted subarrays into single sorted array. Three methods required: mergeSort: Public method called by clients mergeSortHelper: Hides extra parameter required by recursive calls merge: Implements merging process Fundamentals of Java

Merge Sort (cont.) Fundamentals of Java

Merge Sort (cont.) Fundamentals of Java

Figure 12-22: Subarrays generated during calls of mergeSort Merge Sort (cont.) Figure 12-22: Subarrays generated during calls of mergeSort Fundamentals of Java

Figure 12-23: Merging the subarrays generated during a merge sort Merge Sort (cont.) Figure 12-23: Merging the subarrays generated during a merge sort Fundamentals of Java

Merge Sort (cont.) Complexity analysis: Execution time dominated by the two for loops in the merge method Each loops (high + low + 1) times For each recursive stage, O(high + low) or O(n) Number of stages is O(log n), so overall complexity is O(n log n). Fundamentals of Java

Design, Testing, and Debugging Hints When designing a recursive method, ensure: A well-defined stopping state A recursive step that changes the size of the data so the stopping state will eventually be reached Recursive methods can be easier to write correctly than equivalent iterative methods. More efficient code is often more complex. Fundamentals of Java

Summary A recursive method is a method that calls itself to solve a problem. Recursive solutions have one or more base cases or termination conditions that return a simple value or void. Recursive solutions have one or more recursive steps that receive a smaller instance of the problem as a parameter. Fundamentals of Java

Summary (cont.) Some recursive methods combine the results of earlier calls to produce a complete solution. Run-time behavior of an algorithm can be expressed in terms of big-O notation. Big-O notation shows approximately how the work of the algorithm grows as a function of its problem size. Fundamentals of Java

Summary (cont.) There are different orders of complexity such as constant, linear, quadratic, and exponential. Through complexity analysis and clever design, the complexity of an algorithm can be reduced to increase efficiency. Quicksort uses recursion and can perform much more efficiently than selection sort, bubble sort, or insertion sort. Fundamentals of Java