Starting Out with C++, 3 rd Edition Chapter 19 Recursion.

Slides:



Advertisements
Similar presentations
Chapter 17 Linked Lists.
Advertisements

Starting Out with Java: From Control Structures through Objects
Starting Out with C++, 3 rd Edition 1 Chapter 8 – Searching and Sorting Arrays.
 2003 Prentice Hall, Inc. All rights reserved. 1 Recursion Recursive functions –Functions that call themselves –Can only solve a base case If not base.
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.
Copyright © 2008 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Starting Out with C++ Early Objects Sixth Edition Chapter 14: Recursion by.
Chapter 19 Recursion.
 2003 Prentice Hall, Inc. All rights reserved. 1 Sorting Arrays Sorting data –Important computing application –Virtually every organization must sort.
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.
Searching Arrays Linear search Binary search small arrays
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.
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 Chapter Nature of Recursion t Problems that lend themselves to a recursive solution have the following characteristics: –One or more.
 2003 Prentice Hall, Inc. All rights reserved. 1 Functions and Recursion Outline Function Templates Recursion Example Using Recursion: The Fibonacci Series.
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.
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.
Lecture6 Recursion function © by Pearson Education, Inc. All Rights Reserved. 1.
Copyright © 2010 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Starting Out with Programming Logic & Design Second Edition by Tony Gaddis.
Chapter 2 Recursion: The Mirrors. © 2005 Pearson Addison-Wesley. All rights reserved2-2 Recursive Solutions Recursion is an extremely powerful problem-
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.
10/14/2015cosc237/recursion1 Recursion A method of defining a concept which refers to the concept itself A method of solving a problem by reducing it to.
Review Introduction to Searching External and Internal Searching Types of Searching Linear or sequential search Binary Search Algorithms for Linear Search.
1 Lecture 5: Part 1 Searching Arrays Searching Arrays: Linear Search and Binary Search Search array for a key value Linear search  Compare each.
Starting Out with C++, 3 rd Edition 1 Searching an Arrays.
Copyright © 2015, 2012, 2009 Pearson Education, Inc., Publishing as Addison-Wesley All rights reserved. Chapter 8: Searching and Sorting Arrays.
Lecture 16: Searching and Sorting Arrays Professor: Dr. Miguel Alonso Jr. Fall 2008 CGS2423/COP1220.
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.
Concepts of Algorithms CSC-244 Unit 5 and 6 Recursion Shahid Iqbal Lone Computer College Qassim University K.S.A.
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.
Recursion Chapter 12.
Chapter 15 Recursion.
Chapter 14: Recursion Starting Out with C++ Early Objects
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
Chapter 8 – Searching and Sorting Arrays
Searching and Sorting Arrays
Recursive Algorithms 1 Building a Ruler: drawRuler()
Presentation transcript:

Starting Out with C++, 3 rd Edition Chapter 19 Recursion

Starting Out with C++, 3 rd Edition 19.1 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?

Starting Out with C++, 3 rd Edition 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.

Starting Out with C++, 3 rd Edition 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); } return; }

Starting Out with C++, 3 rd Edition 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.

Starting Out with C++, 3 rd Edition 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. Figure 19-1 (on the next slide) illustrates this.

Starting Out with C++, 3 rd Edition Figure st call of the function Value of times : 5 2 nd call of the function Value of times : 4 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. When the function calls itself, a new instance of times is created with the value 4.

Starting Out with C++, 3 rd Edition Figure st call of the function Value of times : 5 2 nd call of the function Value of times : 4 3 rd 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 6th call of the function Value of times : 0 This cycle repeats itself until 0 is passed to to the function. Depth of recursion: 6

Starting Out with C++, 3 rd Edition Program 19-1 // This program demonstrates a simple recursive function. #include // Function prototype void message(int); void main(void) { message(5); }

Starting Out with C++, 3 rd Edition Program 19-1 (continued) //*********************************************************** // Definition of function Message. If the value in times is * // greater than 0, the message is displayed and the * // function is recursively called with the argument * // times - 1. * //*********************************************************** void message(int times) { if (times > 0) { cout << "This is a recursive function.\n"; message(times - 1); } return; }

Starting Out with C++, 3 rd Edition Program 19-1 (continued) Program Output This is a recursive function. This is a recursive function. This is a recursive function. This is a recursive function. This is a recursive function.

Starting Out with C++, 3 rd Edition Program 19-2 // This program demonstrates a simple recursive function. #include // Function prototype void message(int); void main(void) { message(5); }

Starting Out with C++, 3 rd Edition Program 19-2 (continued) //*********************************************************** // Definition of function Message. If the value in times is * // greater than 0, the message is displayed and the * // function is recursively called with the argument * // times - 1. * //*********************************************************** void message(int times) { cout 0) { cout << "This is a recursive function.\n"; message(times - 1); } cout << "Message returning with " << times; cout << " in times.\n"; }

Starting Out with C++, 3 rd Edition Program 19-2 (continued) Program Output Message called with 5 in Times. This is a recursive function. Message called with 4 in Times. This is a recursive function. Message called with 3 in Times. This is a recursive function. Message called with 2 in Times. This is a recursive function. Message called with 1 in Times. This is a recursive function. Message called with 0 in Times. Message returning with 0 in Times. Message returning with 1 in Times. Message returning with 2 in Times. Message returning with 3 in Times. Message returning with 4 in Times. Message returning with 5 in Times.

Starting Out with C++, 3 rd Edition 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.

Starting Out with C++, 3 rd Edition The numChars function 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); } } 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.

Starting Out with C++, 3 rd Edition 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.

Starting Out with C++, 3 rd Edition Program 19-3 // This program demonstrates a recursive function for // counting the number of times a character appears // in a string. #include int numChars(char, char [], int); void main(void) { char array[] = "abcddddef"; cout << "The letter d appears “ << numChars('d', array, 0) << " times\n"; }

Starting Out with C++, 3 rd Edition Program 19-3 (continued) //************************************************ // Function numChars. This recursive function * // counts the number of times the character * // search appears in the string str. The search * // begins at the subscript stored in subscript. * //************************************************ 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); } }

Starting Out with C++, 3 rd Edition Program 19-3 (continued) Program Output The letter d appears 4 times.

Starting Out with C++, 3 rd Edition 19.2 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 *... * nif n > 0 1if n = 0

Starting Out with C++, 3 rd Edition 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 1if 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; }

Starting Out with C++, 3 rd Edition Program 19-4 // This program demonstrates a recursive function to // calculate the factorial of a number. #include // Function prototype int factorial(int); void main(void) { int number; cout > number; cout << "The factorial of " << number << " is "; cout << factorial(number) << endl; }

Starting Out with C++, 3 rd Edition Program 19-4 //************************************************************** // Definition of factorial. A recursive function to calculate * // the factorial of the parameter, num. * //************************************************************** int factorial(int num) { if (num > 0) return num * factorial(num - 1); else return 1; }

Starting Out with C++, 3 rd Edition Program 19-4 Program Output with Example Input Enter an integer value and I will display its factorial: 4 The factorial of 4 is 24

Starting Out with C++, 3 rd Edition 19.3 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) 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. This is demonstrated in Program 19-5.

Starting Out with C++, 3 rd Edition Program 19-5 // This program demonstrates a recursive function to calculate // the greatest common divisor (gcd) of two numbers. #include // Function prototype int gcd(int, int); void main(void) { int num1, num2; cout > num1 >> num2; cout << "The greatest common divisor of " << num1; cout << " and " << num2 << " is "; cout << gcd(num1, num2) << endl; }

Starting Out with C++, 3 rd Edition Program 19-5 //********************************************************* // Definition of gcd. This function uses recursion to * // calculate the greatest common divisor of two integers, * // passed into the parameters x and y. * //********************************************************* int gcd(int x, int y) { if (x % y == 0) return y; else return gcd(y, x % y); } Program Output with Example Input Enter two integers: The greatest common divisor of 49 and 28 is 7

Starting Out with C++, 3 rd Edition 19.4 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, …

Starting Out with C++, 3 rd Edition Solving Recursively Defined Problems The Fibonacci series can be defined as: F 0 = 0, F 1 = 1, F N = F N-1 + F N-2 for N  2.

Starting Out with C++, 3 rd Edition 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); }

Starting Out with C++, 3 rd Edition Program 19-6 // This programs demonstrates a recursive function // that calculates Fibonacci numbers. #include // Function prototype int fib(int); void main(void) { cout << "The first 10 Fibonacci numbers are:\n"; for (int x = 0; x < 10; x++) cout << fib(x) << " "; cout << endl; }

Starting Out with C++, 3 rd Edition Program 19-6 (continued) //***************************************** // Function fib. Accepts an int argument * // in n. This function returns the nth * // Fibonacci number. * //***************************************** int fib(int n) { if (n <= 0) return 0; else if (n == 1) return 1; else return fib(n - 1) + fib(n - 2); }

Starting Out with C++, 3 rd Edition Program 19-6 (continued) Program Output The first 10 Fibonacci numbers are:

Starting Out with C++, 3 rd Edition 19.5 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 in Chapter 17.

Starting Out with C++, 3 rd Edition Counting the Nodes in the List int FloatList::countNodes(ListNode *nodePtr) { if (nodePtr != NULL) return 1 + countNodes(nodePtr->next); else return 0; } The base case for the function is nodePtr being equal to NULL.

Starting Out with C++, 3 rd Edition Counting the Nodes in the List The function's recursive logic can be expressed as: If the current node has a value Return 1 + the number of the remaining nodes. Else Return 0. end If.

Starting Out with C++, 3 rd Edition Program 19-7 #include #include "FloatList2.h“ void main(void) { FloatList list; for (int x = 0; x < 10; x++) list.insertNode(x); cout << "The number of nodes is “ << list.numNodes() << endl; } Program Output The number of nodes is 10

Starting Out with C++, 3 rd Edition Displaying the List Nodes in Reverse Order void FloatList::showReverse(ListNode *nodePtr) { if (nodePtr != NULL) { showReverse(nodePtr->next); cout value << " "; } } The base case for the function is nodePtr being equal to NULL.

Starting Out with C++, 3 rd Edition Program 19-8 // This program demonstrates the FloatList class's // recursive function for displaying the list's nodes // in reverse. #include #include "FloatList2.h“ void main(void) { FloatList list; for (float x = 1.5; x < 15; x += 1.1) list.appendNode(x); cout << "Here are the values in the list:\n"; list.displayList(); cout << "Here are the values in reverse order:\n"; list.displayBackwards(); }

Starting Out with C++, 3 rd Edition Program 19-8 (continued) Program Output Here are the values in the list: Here are the values in reverse order:

Starting Out with C++, 3 rd Edition 19.6 A Recursive Binary Search Function The binary search algorithm, which you learned about in Chapter 8, 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.

Starting Out with C++, 3 rd Edition A Recursive Binary Search Function A recursive binary search function is shown below. int binarySearch(int array[], int first, int last, int value) { int middle;// Mid point of search 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); }

Starting Out with C++, 3 rd Edition 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 3 rd parameter, last, holds the subscript of the last element in the search range. The 4 th 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.

Starting Out with C++, 3 rd Edition Program 19-9 // This program demonstrates the recursive binarySearch function, which // performs a binary search on an integer array. #include // Function prototype int binarySearch(int [], int, int, int); const int arrSize = 20; void main(void) { int tests[arrSize] = {101, 142, 147, 189, 199, 207, 222, 234, 289, 296, 310, 319, 388, 394, 417, 429, 447, 521, 536, 600}; int results, empID; cout > empID;

Starting Out with C++, 3 rd Edition Program 19-9 (continued) results = binarySearch(tests, 0, arrSize - 1, empID); if (results == -1) cout << "That number does not exist in the array.\n"; else { cout << "That ID is found at element " << results; cout << " in the array\n"; } } //*************************************************************** // The binarySearch function performs a recursive binary search * // on a range of elements of an integer array passed into the * // parameter array.The parameter first holds the subscript of * // the range's starting element, and last holds the subscript * // of the ranges's last element. The paramter value holds the * // the search value. If the search value is found, its array * // subscript is returned. Otherwise, -1 is returned indicating * // the value was not in the array. * //***************************************************************

Starting Out with C++, 3 rd Edition Program 19-9 int binarySearch(int array[], int first, int last, int value) { int middle;// Mid point of search 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); } Program Output with Example Input Shown in Bold Enter the Employee ID you wish to search for: 521 [Enter] That ID is found at element 17 in the array

Starting Out with C++, 3 rd Edition 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 in Figure 19-4.

Starting Out with C++, 3 rd Edition 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.

Starting Out with C++, 3 rd Edition 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.

Starting Out with C++, 3 rd Edition The QuickSort Algorithm The C++ Code: void quickSort(int set[], int start, int end) { int pivotPoint; if (start < end) { // Get the pivot point. pivotPoint = partition(set, start, end); // Sort the first sub list. quickSort(set, start, pivotPoint - 1); // Sort the second sub list. quickSort(set, pivotPoint + 1, end); } }

Starting Out with C++, 3 rd Edition The QuickSort Algorithm The partition Function: 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]); } } exchange(set[start], set[pivotIndex]); return pivotIndex; }

Starting Out with C++, 3 rd Edition The QuickSort Algorithm The exchange Function: void exchange(int &value1, int &value2) { int temp = value1; value1 = value2; value2 = temp; }

Starting Out with C++, 3 rd Edition Program // This program demonstrates the QuickSort Algorithm #include // Function prototypes void quickSort(int [], int, int); int partition(int [], int, int); void exchange(int &, int &); void main(void) { int array[10] = {7, 3, 9, 2, 0, 1, 8, 4, 6, 5}; int x;// Counter for (x = 0; x < 10; x++) cout << array[x] << " "; cout << endl; quickSort(array, 0, 9); for (x = 0; x < 10; x++) cout << array[x] << " "; cout << endl; } The code for the remainder of the program was previously shown…

Starting Out with C++, 3 rd Edition Program Program Output