Some Advanced Features of Procedures. Recursion Recursive Calls –A procedure can call itself (Self Recursion) –A can call B, B calls C, etc, Z calls A.

Slides:



Advertisements
Similar presentations
3/25/2017 Chapter 16 Recursion.
Advertisements

Towers of Hanoi Move n (4) disks from pole A to pole C such that a disk is never put on a smaller disk A BC ABC.
C++ Programming:. Program Design Including
Chapter 7 Introduction to Procedures. So far, all programs written in such way that all subtasks are integrated in one single large program. There is.
Recursion Ellen Walker CPSC 201 Data Structures Hiram College.
Stephen P. Carl - CS 2421 Recursive Sorting Algorithms Reading: Chapter 5.
Factorial Recursion stack Binary Search Towers of Hanoi
Recursive methods. Recursion A recursive method is a method that contains a call to itself Often used as an alternative to iteration when iteration is.
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. Idea: Some problems can be broken down into smaller versions of the same problem Example: n! 1*2*3*…*(n-1)*n n*factorial of (n-1)
Chapter 15 Recursive Algorithms. 2 Recursion Recursion is a programming technique in which a method can call itself to solve a problem A recursive definition.
Copyright © 2008 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Starting Out with Java: Early Objects Third Edition by Tony Gaddis Chapter.
Recursion Chapter 5 Outline Induction Linear recursion –Example 1: Factorials –Example 2: Powers –Example 3: Reversing an array Binary recursion –Example.
Recursion.  Identify recursive algorithms  Write simple recursive algorithms  Understand recursive function calling  With reference to the call stack.
Sorting (Part II: Divide and Conquer) CSE 373 Data Structures Lecture 14.
Recursion Chapter 7 Copyright ©2012 by Pearson Education, Inc. All rights reserved.
1 Recursion Dr. Bernard Chen Ph.D. University of Central Arkansas.
Recursion. Basic problem solving technique is to divide a problem into smaller subproblems These subproblems may also be divided into smaller subproblems.
Chapter 13 Recursion. Topics Simple Recursion Recursion with a Return Value Recursion with Two Base Cases Binary Search Revisited Animation Using Recursion.
© 2010 Pearson Addison-Wesley. All rights reserved. Addison Wesley is an imprint of Chapter 15: Recursion Starting Out with Java: From Control Structures.
Copyright © 2011 Pearson Education, Inc. Starting Out with Java: Early Objects Fourth Edition by Tony Gaddis Chapter 14: Recursion.
CHAPTER 02 Recursion Compiled by: Dr. Mohammad Omar Alhawarat.
Chapter 15: Advanced Topics: Introducing Data Structures and Recursion Visual Basic.NET Programming: From Problem Analysis to Program Design.
Week 8 Improving on building blocks Recursive procedures.
224 3/30/98 CSE 143 Recursion [Sections 6.1, ]
Computer Science Department Data Structure & Algorithms Lecture 8 Recursion.
Reading – Chapter 10. Recursion The process of solving a problem by reducing it to smaller versions of itself Example: Sierpinski’s TriangleSierpinski’s.
Review Introduction to Searching External and Internal Searching Types of Searching Linear or sequential search Binary Search Algorithms for Linear Search.
# 1# 1 VBA Recursion What is the “base case”? What is the programming stack? CS 105 Spring 2010.
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.
Functions-Recall 1. 2 Parameter passing & return void main() { int x=10, y=5; printf (“M1: x = %d, y = %d\n”, x, y); interchange (x, y); printf (“M2:
By: Lokman Chan Recursive Algorithm Recursion Definition: A function that is define in terms of itself. Goal: Reduce the solution to.
ISOM MIS 215 Module 4 – Recursion. ISOM Where are we? 2 Intro to Java, Course Java lang. basics Arrays Introduction NewbieProgrammersDevelopersProfessionalsDesigners.
©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display. Chapter 15 * Recursive Algorithms.
Lecture 7. Solution by Substitution Method T(n) = 2 T(n/2) + n Substitute n/2 into the main equation 2T(n/2) = 2(2(T(n/4)) + n/2) = 4T(n/4) + n And T(n)
Recursive Algorithms A recursive algorithm calls itself to do part of its work The “call to itself” must be on a smaller problem than the one originally.
Recursive Algorithm (4.4) An algorithm is called recursive if it solves a problem by reducing it to an instance of the same problem with smaller input.
1 Chapter 8 Recursion. 2 Recursive Function Call a recursion function is a function that either directly or indirectly makes a call to itself. but we.
1 CS1120: Recursion. 2 What is Recursion? A method is said to be recursive if the method definition contains a call to itself A recursive method is a.
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! =
CMPT 238 Data Structures More on Sorting: Merge Sort and Quicksort.
CS 116 Object Oriented Programming II Lecture 13 Acknowledgement: Contains materials provided by George Koutsogiannakis and Matt Bauer.
Data Structures I (CPCS-204) Week # 5: Recursion Dr. Omar Batarfi Dr. Yahya Dahab Dr. Imtiaz Khan.
CSC 143 P 1 CSC 143 Recursion [Chapter 5]. CSC 143 P 2 Recursion  A recursive definition is one which is defined in terms of itself  Example:  Compound.
1 CSC 143 Recursion [Reading: Chapter 17]. 2 Recursion  A recursive definition is one which is defined in terms of itself.  Example:  Sum of the first.
Recursion Chapter 10 Carrano, Data Structures and Abstractions with Java, Second Edition, (c) 2007 Pearson Education, Inc. All rights reserved X.
Recursion Chapter 10 Slides by Steve Armstrong LeTourneau University Longview, TX  2007,  Prentice Hall.
1 Dr. Chow-Sing LinRecursion - CH 10 Problem Solving and Program Design in C Chapter 9 Recursion Chow-Sing Lin.
CS212: Data Structures and Algorithms
Chapter Topics Chapter 16 discusses the following main topics:
Chapter 15 Recursion.
Lesson #6 Modular Programming and Functions.
Lesson #6 Modular Programming and Functions.
Towers of Hanoi Move n (4) disks from pole A to pole C
Chapter 15 Recursion.
To understand recursion, you have to understand recursion!
STACKS.
Recursion Chapter 10.
Data Structures Recursion CIS265/506: Chapter 06 - Recursion.
Lesson #6 Modular Programming and Functions.
CS1120: Recursion.
CS201: Data Structures and Discrete Mathematics I
Recursion Data Structures.
Data Structures Review Session
Announcements Last … First … … quiz section … office hour
Lesson #6 Modular Programming and Functions.
CSC 143 Recursion.
Dr. Sampath Jayarathna Cal Poly Pomona
Advanced Analysis of Algorithms
Presentation transcript:

Some Advanced Features of Procedures

Recursion Recursive Calls –A procedure can call itself (Self Recursion) –A can call B, B calls C, etc, Z calls A (Mutual Recursion) Powerful Abstraction –Many functions are recursive in nature –Factorial, Fibonacci, etc. fact(0) = 1 fact(n+1) = (n+1) * fact(n) fib(0) = 1 fib(1) = 1 fib(n+2) = fib(n+1) + fib(n) Such functions can be directly encoded

Complex control Flow Recursive functions abstracts out complex control flow –Different instance of the same procedure exists at a time –Termination and resumption of different instances correctly –Last called is exited first ( Last In First Out LIFO) –Use of stack data structure (stack overflow) –A lot of overhead in implementation

Factorial Example Program fact Implicit none integer:: N, z read *, N call fct(N, z) print *, z contains recursive subroutine fct(M, y) implicit none integer, intent(in):: M integer, intent(out):: y if (M >= 1) then call fct(M - 1, y) y = M * y else y = 1 endif end subroutine end program

Recursive Function Program fact implicit none integer:: N, z read *, N z = fct(N) print *, z contains recursive integer function fct(M) result(answer) implicit none integer:: M, answer if (M /= 0) then answer = M * fct(M - 1) else answer = 1 endif end function end program

Fibonacci Numbers Program fibonacci implicit none integer:: N, z read *, N call fib(N, z) print *, z contains recursive subroutine fib(M, y) implicit none integer, intent(in):: M integer, intent(out):: y integer:: y1, y2 if (M > 1) then call fib(M - 1, y1) call fib(M - 1, y2) y = y1 + y2 else y = 1 endif end subroutine end program

Tower of Hanoi Problem Initial Configuration Original pole Final poleSpare pole

Final Configuration Original poleSpare poleFinal pole

Rules Only one disc can be moved at a time bigger disc never placed over a smaller one only one temporary pole How to solve the problem?

Divide and Conquer Reduce the problem size! How? Consider the following situation: Original pole Finalpolesparepole

Sub problems How to transfer smaller (n-1) discs from initial pole to temporary pole? How to transfer smaller (n-1) discs to the final pole from temporary pole? These two problems are similar but with the problem size reduced and the initial and final poles being different How to solve the sub problems? –Reduce further down (recursion) When (n-1) = 1, the problem becomes trivial

Sub problems Algorithm hanoi_tower (ndisks, init_pole, spare_pole, fin_pole) 1.If (ndisks > 0) then 1.1 hanoi_tower(ndisks - 1, init_pole, fin_pole, spare_pole) 1.2 transfer_disk(init_pole, fin_pole) 1.3 hanoi_tower(ndisks - 1, spare_pole, init_pole, fin_pole) end When the first argument is 0, no action, only empty recursive calls Simplify by removing the recursive calls for the case ndiscs = 1

Fortran Solution requires modeling the problem domain Need software models for all real objects Discs, poles, movements etc. Discs as numbers, poles as stacks, movements as pushes and pops

Quick Sort quick sort is another sorting algorithm which when implemented properly gives the fastest known sorting algorithm for random inputs useful for sorting arrays rather than lists main idea – pick one element, put it in its correct position, all elements < than it to its left and others to its right recursively sort left and right halves expressed easily using recursion

Quick Sort recursive subroutine quick_sort(a) implicit none integer, dimension(:), intent(inout) :: a integer :: i,n n = size(a) if ( n > 1) then call partition(a,i) call quick_sort(a(:i-1)) call quick_sort(a(i+1:)) end if contains

Partition subroutine partition(a,j) integer, dimension(:), intent(inout) :: a integer,intent(out) :: j integer :: i,temp i = 1 ; j = size(a) do if ( i > j ) exit if (a(i) > a(1)) exit i = i+1 end do

Partition do if ((j < i).or. (a(j) <= a(1))) exit j = j-1 end do if ( i >= j) exit temp = a(i) a(i) = a(j) a(j) = temp end do temp = a(j) ; a(j) = a(1) ; a(1) = temp end subroutine partition end subroutine quick_sort

Tail Recursion Any number of recursive calls Complex control flow Difficult to understand Linear Recursion Tail recursion –The recursive call occurs as the last statement –Can be easily translated to iterative programs General recursive programs can also be translated to iterative programs But this requires, in general, a stack (FIFO data structure) Computationally expensive

Keyword Parameters The actual parameter list should match the dummy parameter list in order might prove to be cumbersome when argument lists are large keyword argument is a solution to this problem Suppose test(first, second, third)... end subroutine test the following calls are legal: test(3, 6, 7) test(first = 3, third = 7, second = 6) test(3, third = 7, second = 6) Explicit interface for the procedure required Declare it in a module which can be `used' by the calling routine

Optional Parameters Parameters can be optional Declare –integer, intent(in), optional:: limit The actual argument for limit can be left out in a call and default values can be used A logical function to test whether an optional argument is present or not if (PRESENT(limit) then... else... endif