Chapter 19 Recursion.

Slides:



Advertisements
Similar presentations
Starting Out with Java: From Control Structures through Objects
Advertisements

Ver. 1.0 Session 5 Data Structures and Algorithms Objectives In this session, you will learn to: Sort data by using quick sort Sort data by using merge.
Lesson 19 Recursion CS1 -- John Cole1. Recursion 1. (n) The act of cursing again. 2. see recursion 3. The concept of functions which can call themselves.
Recursion. Binary search example postponed to end of lecture.
Copyright © 2008 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Starting Out with C++ Early Objects Sixth Edition Chapter 14: Recursion by.
Recursion.
1 Section 3.5 Recursive Algorithms. 2 Sometimes we can reduce solution of problem to solution of same problem with set of smaller input values When such.
Chapter 19 Recursion.
 2003 Prentice Hall, Inc. All rights reserved Sorting Arrays Sorting data –Important computing application –Virtually every organization must sort.
1 Chapter 7 Recursion. 2 What Is Recursion? l Recursive call A method call in which the method being called is the same as the one making the call l Direct.
Starting Out with C++: Early Objects 5/e © 2006 Pearson Education. All Rights Reserved Starting Out with C++: Early Objects 5 th Edition Chapter 14 Recursion.
Copyright © 2008 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Starting Out with Java: Early Objects Third Edition by Tony Gaddis Chapter.
Starting Out with C++: Early Objects 5/e © 2006 Pearson Education. All Rights Reserved Starting Out with C++: Early Objects 5 th Edition Chapter 9 Searching.
Recursion In general there are two approaches to writing repetitive algorithms. One uses loops(while, do while and for): the other uses recursion. Recursion.
Chapter 8 ARRAYS Continued
Copyright © 2009 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Chapter 19: Recursion.
1 C++ Plus Data Structures Nell Dale Chapter 7 Programming with Recursion Slides by Sylvia Sorkin, Community College of Baltimore County - Essex Campus.
Copyright © 2014, 2008 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Starting Out with C++ Early Objects Eighth Edition by Tony Gaddis,
Copyright 2003 Scott/Jones Publishing Standard Version of Starting Out with C++, 4th Edition Chapter 19 Recursion.
Chapter 14: Recursion Starting Out with C++ Early Objects
Recursion, Complexity, and Searching and Sorting By Andrew Zeng.
Recursion. Basic problem solving technique is to divide a problem into smaller sub problems These sub problems may also be divided into smaller sub problems.
Chapter 13 Recursion. Topics Simple Recursion Recursion with a Return Value Recursion with Two Base Cases Binary Search Revisited Animation Using Recursion.
Chapter 3 Recursion: The Mirrors. © 2004 Pearson Addison-Wesley. All rights reserved 3-2 Recursive Solutions Recursion –An extremely powerful problem-solving.
Copyright © 2010 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Chapter 8: Searching and Sorting Arrays.
Copyright © 2012 Pearson Education, Inc. Chapter 8: Searching and Sorting Arrays.
Recursion l Powerful Tool l Useful in simplifying a problem (hides details of a problem) l The ability of a function to call itself l A recursive call.
© 2010 Pearson Addison-Wesley. All rights reserved. Addison Wesley is an imprint of Chapter 15: Recursion Starting Out with Java: From Control Structures.
Chapter 11Java: an Introduction to Computer Science & Programming - Walter Savitch 1 Chapter 11 l Basics of Recursion l Programming with Recursion Recursion.
Copyright © 2011 Pearson Education, Inc. Starting Out with Java: Early Objects Fourth Edition by Tony Gaddis Chapter 14: Recursion.
15-1 Chapter-18: Recursive Methods –Introduction to Recursion –Solving Problems with Recursion –Examples of Recursive Methods.
Copyright © 2015 Pearson Education, Inc. Publishing as Pearson Addison-Wesley C H A P T E R 12 Recursion.
Copyright © 2010 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Starting Out with Programming Logic & Design Second Edition by Tony Gaddis.
COSC 2006 Data Structures I Recursion II
Chapter 2 Recursion: The Mirrors. © 2005 Pearson Addison-Wesley. All rights reserved2-2 Recursive Solutions Recursion is an extremely powerful problem-
1 Programming with Recursion. 2 Recursive Function Call A recursive call is a function call in which the called function is the same as the one making.
SEARCHING UNIT II. Divide and Conquer The most well known algorithm design strategy: 1. Divide instance of problem into two or more smaller instances.
1 Lecture 14 Chapter 18 - Recursion. 2 Chapter 18 Topics l Meaning of Recursion l Base Case and General Case in Recursive Function Definitions l Writing.
1 Chapter 13 Recursion. 2 Chapter 13 Topics l Meaning of Recursion l Base Case and General Case in Recursive Function Definitions l Writing Recursive.
1 Recursion. 2 Chapter 15 Topics  Meaning of Recursion  Base Case and General Case in Recursive Function Definitions  Writing Recursive Functions with.
1 C++ Plus Data Structures Nell Dale Chapter 7 Programming with Recursion Slides by Sylvia Sorkin, Community College of Baltimore County - Essex Campus.
Review Introduction to Searching External and Internal Searching Types of Searching Linear or sequential search Binary Search Algorithms for Linear Search.
Copyright © 2015, 2012, 2009 Pearson Education, Inc., Publishing as Addison-Wesley All rights reserved. Chapter 8: Searching and Sorting Arrays.
C++ Programming: From Problem Analysis to Program Design, Second Edition Chapter 19: Searching and Sorting.
LAB#7. Insertion sort In the outer for loop, out starts at 1 and moves right. It marks the leftmost unsorted data. In the inner while loop, in starts.
CSC 211 Data Structures Lecture 13
Searching & Sorting Programming 2. Searching Searching is the process of determining if a target item is present in a list of items, and locating it A.
1 Recursion. 2 Chapter 15 Topics  Meaning of Recursion  Base Case and General Case in Recursive Function Definitions  Writing Recursive Functions with.
Chapter 7 Programming with Recursion. What Is Recursion? Recursive call A method call in which the method being called is the same as the one.
PREVIOUS SORTING ALGORITHMS  BUBBLE SORT –Time Complexity: O(n 2 ) For each item, make (n –1) comparisons Gives: Comparisons = (n –1) + (n – 2)
Starting Out with C++, 3 rd Edition Chapter 19 Recursion.
Copyright © 2015, 2012, 2009 Pearson Education, Inc., Publishing as Addison-Wesley All rights reserved. Chapter 8: Searching and Sorting Arrays.
Maitrayee Mukerji. Factorial For any positive integer n, its factorial is n! is: n! = 1 * 2 * 3 * 4* ….* (n-1) * n 0! = 1 1 ! = 1 2! = 1 * 2 = 2 5! =
CS 116 Object Oriented Programming II Lecture 13 Acknowledgement: Contains materials provided by George Koutsogiannakis and Matt Bauer.
Program Development and Design Using C++, Third Edition
Searching and Sorting Arrays
Chapter Topics Chapter 16 discusses the following main topics:
Chapter 19: Recursion.
Topic 6 Recursion.
Chapter 15 Recursion.
OBJECT ORIENTED PROGRAMMING II LECTURE 23 GEORGE KOUTSOGIANNAKIS
Chapter 15 Recursion.
Chapter 14: Recursion Starting Out with C++ Early Objects
Programming with Recursion
Chapter 14: Recursion Starting Out with C++ Early Objects
Recursion "To understand recursion, one must first understand recursion." -Stephen Hawking.
Chapter 14: Recursion Starting Out with C++ Early Objects
Searching and Sorting Arrays
Searching and Sorting Arrays
Recursive Algorithms 1 Building a Ruler: drawRuler()
Presentation transcript:

Chapter 19 Recursion

Introduction to Recursion A recursive function is one that calls itself. void message(void) { cout << "This is a recursive function.\n"; message(); } The function above displays the string "This is a recursive function.\n", and then calls itself. Can you see a problem with the function?

Recursion The function is like an infinite loop because there is no code to stop it from repeating. Like a loop, a recursive function must have some algorithm to control the number of times it repeats.

Recursion Like a loop, a recursive function must have some algorithm to control the number of times it repeats. Shown below is a modification of the message function. It passes an integer argument, which holds the number of times the function is to call itself. void message( int times ) { if ( times > 0 ) { cout << "This is a recursive function.\n"; message( times ‑ 1 ); } // if return; } // message

Recursion The function contains an if/else statement that controls the repetition. As long as the times argument is greater than zero, it will display the message and call itself again. Each time it calls itself, it passes times - 1 as the argument.

Recursion For example, let's say a program calls the function with the following statement:   Message(5); The argument, 5, will cause the function to call itself 5 times. The first time the function is called, the if statement will display the message and then call itself with 4 as the argument. The next slide illustrates this.

Recursion Each time the function is called, a new instance of the times parameter is created. In the first call to the function, times is set to 5. 1st call of the function Value of times: 5 When the function calls itself, a new instance of times is created with the value 4. 2nd call of the function Value of times: 4

This cycle repeats itself until 0 is passed to to the function. 1st call of the function Value of times: 5 This cycle repeats itself until 0 is passed to to the function. 2nd call of the function Value of times: 4 3rd call of the function Value of times: 3 4th call of the function Value of times: 2 5th call of the function Value of times: 1 Depth of recursion: 6 6th call of the function Value of times: 0

Recursion The role of recursive functions in programming is to break complex problems down to a solvable problem. The solvable problem is known as the base case. A recursive function is designed to terminate when it reaches its base case.

The numChars function The function's parameters are: int numChars ( char search, char str[], int subscript ) { if ( str[subscript] == '\0‘ ) return 0; else { if ( str[subscript] == search ) return 1 + numChars( search, str, subscript+1 ); else return numChars(search, str, subscript+1); } // if } // numChars The function's parameters are: search: The character to be searched for and counted. str: An array containing the string to be searched. subscript: The starting subscript for the search.

The numChars function The first if statement determines if the end of the string has been reached:   if ( str[subscript] == '\0‘ ) If so, the function returns 0, indicating there are no more characters to count. Otherwise, the following if/else statement is executed: if (str[subscript] == search) return 1 + numChars(search, str, subscript+1); else return numChars(search, str, subscript+1); If str[subscript] contains the search character, the function performs a recursive call. The return statement returns 1 + the number of times the search character appears in the string, starting at subscript + 1. If str[subscript] does not contain the search character, a recursive call is made to search the remainder of the string.

Direct and Indirect Recursion These examples show recursive functions that directly call themselves. This is known as direct recursion. There is also the possibility of creating indirect recursion in a program. This occurs when function A calls function B, which in turn calls function A.

The Recursive Factorial Function In mathematics, the notation n! represents the factorial of the number n. The factorial of a number is defined as:   n! = 1 * 2 * 3 * ... * n if n > 0 1 if n = 0

The Recursive Factorial Function Another way of defining the factorial of a number, using recursion, is:  Factorial(n) = n * Factorial(n - 1) if n > 0 1 if n = 0 The following C++ function implements the recursive definition shown above:  int factorial( int num ) { if ( num > 0 ) return num * factorial( num – 1 ); else return 1; } // factorial

The Recursive gcd Function Our next example of recursion is the calculation of the greatest common divisor, or GCD, of two numbers. Using Euclid's Algorithm, the GCD of two positive integers, x and y, is:   GCD(x, y) = y; if y divides x evenly GCD(y, remainder of y/x); otherwise The definition above states that the GCD of x and y is y if x/y has no remainder. Otherwise, the answer is the GCD of y and the remainder of x/y.

gcd Function int gcd ( int x, int y ) { if ( x % y == 0 ) return y; else return gcd( y, x % y ); } // gcd

Solving Recursively Defined Problems Some mathematical problems are designed to be solved recursively. One example is the calculation of Fibonacci numbers, which are the following sequence: 0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, 233, …

Solving Recursively Defined Problems The Fibonacci series can be defined as:   F0 = 0, F1 = 1, FN = FN-1 + FN-2 for N  2.

Solving Recursively Defined Problems A recursive C++ function to calculate the nth number in the Fibonacci series is shown below . int fib ( int n ) { if ( n <= 0 ) return 0; else if ( n == 1 ) return 1; else return fib( n – 1 ) + fib( n – 2 ); } // fib

Recursive Linked List Operations Recursion may be used in some operations on linked lists. We will look at functions that: Count the number of nodes in a list, and Display the value of the list nodes in reverse order. We will use the FloatList class developed before.

Counting the Nodes in the List We want to count the number of nodes in a list. The idea is shown below:   If the current node has a value Return 1 + the number of the remaining nodes. Else Return 0. end If.

Counting the Nodes in the List int FloatList::countNodes ( Node *nodePtr ) { if ( nodePtr ) return 1 + countNodes( nodePtr->next ); else return 0; } // FloatList::countNodes The base case for the function is nodePtr being equal to NULL.

Displaying the List Nodes in Reverse Order void FloatList::showReverse ( Node *nodePtr ) { if ( nodePtr ) { showReverse( nodePtr->next ); cout << nodePtr->value << " "; } // if } // FloatList::showReverse The base case for the function is nodePtr being equal to NULL.

A Recursive Binary Search Function The binary search algorithm, which you learned previously, can be implemented recursively. For example, the procedure can be expressed as: If array[middle] equals the search value, then the value is found.  Else, if array[middle] is less than the search value, perform a binary search on the upper half of the array.  Else, if array[middle] is greater than the search value, perform a binary search on the lower half of the array.

A Recursive Binary Search Function int binarySearch ( int array[], int first, int last, int value ) { int middle;   if ( first > last ) return -1; middle = ( first + last ) / 2; if ( array[middle] == value ) return middle; if ( array[middle] < value ) return binarySearch( array, middle+1,last,value ); else return binarySearch( array, first,middle-1,value ); } // binarySearch

A Recursive Binary Search Function  int binarySearch(int array[], int first, int last, int value) The 1st parameter, array, is the array to be searched. The 2nd parameter, first, holds the subscript of the first element in the search range (the portion of the array to be searched). The 3rd parameter, last, holds the subscript of the last element in the search range. The 4th parameter, value, holds the value to be searched for. This function returns the subscript of the value if it is found, or -1 if the value is not found.

The QuickSort Algorithm Can be used to sort lists stored in arrays or linear linked lists. It sorts a list by dividing it into two sublists. Between the sublists is a selected value known as the pivot. This is illustrated below.

The QuickSort Algorithm Once a pivot value has been selected, the algorithm exchanges the other values in the list until all the elements in sublist 1 are less than the pivot, and all the elements in sublist 2 are greater than the pivot. Once this is done, the algorithm repeats the procedure on sublist 1, and then on sublist 2. The recursion stops when there is only one element in a sublist. At that point the original list is completely sorted.

The QuickSort Algorithm The algorithm is coded primarily in two functions: QuickSort and Partition. QuickSort is a recursive function. Its pseudocode is shown below. QuickSort: If Starting Index < Ending Index Partition the List around a Pivot. QuickSort Sublist 1. QuickSort Sublist 2. end If.

The QuickSort Algorithm void quickSort ( int set[], int start, int end ) { int pivotPoint;   if ( start < end ) { pivotPoint = partition( set, start, end ); quickSort( set, start, pivotPoint – 1 ); quickSort( set, pivotPoint + 1, end ); } // if } // quickSort

The QuickSort Algorithm int partition ( int set[], int start, int end ) { int pivotValue, pivotIndex, mid; mid = (start + end) / 2; exchange(set[start], set[mid]); pivotIndex = start; pivotValue = set[start]; for ( int scan = start + 1; scan <= end; scan++ ) { if ( set[scan] < pivotValue ) { pivotIndex++; exchange(set[pivotIndex], set[scan]); } // if } // for exchange(set[start], set[pivotIndex]); return pivotIndex; } // partition

The QuickSort Algorithm void exchange ( int &value1, int &value2 ) { int temp = value1; value1 = value2; value2 = temp; } // exchange

Exhaustive Algorithms An exhaustive algorithm is one that finds a best combination of items by looking at all the possible combinations.

Exhaustive Algorithms For example, consider all the different ways you can make change for $1.00 using our system of coins:   1 dollar piece, or 2 fifty-cent pieces, or 4 quarters, or 1 fifty-cent piece and 2 quarters, or 3 quarters, 2 dimes, and 1 nickel, or … there are many more possibilities.

Exhaustive Algorithms Although there are many ways to make change for $1.00, some ways are better than others. For example, you would probably rather give a single dollar piece instead of 100 pennies.  An algorithm that looks at all the possible combinations of items in order to find the best combination of items is called an exhaustive algorithm.

Making Change void makeChange ( int coinsLeft, int amount, int coinsUsed[], int numCoinsUsed ) { int coinPos, // To calculate array position of coin being used count; // Loop counter if ( coinsLeft == 0 ) // If no more coins are left return; else if ( amount < 0 ) // If amount to make change for is negative return; else if ( amount == 0 ) // If solution is found { if ( numCoinsUsed < numBestCoins ) { for ( count = 0; count < numCoinsUsed; count++) bestCoins[count] = coinsUsed[count]; numBestCoins = numCoinsUsed; } // if numSolutions++; return; } // else if

Making Change (cont) coinPos = numCoins - coinsLeft; coinsUsed[numCoinsUsed] = coinValues[coinPos]; makeChange( coinsLeft, amount - coinValues[coinPos], coinsUsed, numCoinsUsed + 1); makeChange(coinsLeft - 1, amount, coinsUsed, numCoinsUsed); } // makeChange