18
What is recursion? Imagine checking the dictionary for “apple a round fruit with a firm white flesh and a green, red or yellow skin the usually sweet-tasting part of a tree or bush which holds seeds and which can be eaten a tall plant which has a wooden trunk and branches that grow from its upper part You are repeating the same thing with another input, each time “closer” to the “end Recursion is a special function that calls itself until some condition is satisfied

What is recursion? Imagine checking the dictionary for “apple” a round fruit with a firm white flesh and a green, red or yellow skin the usually sweet-tasting

Embed Size (px)

Citation preview

  • What is recursion?Imagine checking the dictionary for applea round fruit with a firm white flesh and a green, red or yellow skinthe usually sweet-tasting part of a tree or bush which holds seeds and which can be eatena tall plant which has a wooden trunk and branches that grow from its upper partYou are repeating the same thing with another input, each time closer to the endRecursion is a special function that calls itself until some condition is satisfied

  • When do we need recursion?There are times when a problem can be expressed in a simpler version of itself, in particular:You repeat the same thing again & again, except you change the input a bitE.g. n! = n * (n-1)!, 2n = 2 * 2n-1You know at certain point it will endE.g. n = 1 for factorial, n = 0 for power of 2

  • Why do we need recursion? For simplicity and elegancyE.g. calculating factorialsint fac(int numb){ if(numb1){ product *= numb; numb--; } return product;}Recursive versionIterative version

  • Examples of recursionMathematical functionsE.g. factorial, exponential, Fibonacci numbersSorting algorithmsE.g. mergesort, quicksortSearch functionsE.g. binary search, BFS, DFS

  • Examples of recursionThe binary searchAssume the search array is sortedGiven a key, each time we can reduce half of the search size, and repeat the search process. We stop when either we find a match, or the search size becomes 1The steps work like a recursion!

  • Examples of recursionBinary search (for value 5)View the range as 3 parts: 1)left; 2)middle; 3)right If middle value == key (5), done. Otherwise decide where the target value would be

    So each time the to-be-searched range shrinks by half, until you are left with a size 1 range

  • Forms of recursionStandard recursion

    Mutual recursionint sum(int n) { if (n=0 { if (n==0) return false; else return isEven(n-1); }

  • Facts of recursionMathematically equivalent to the imperative languages, which uses loopsi.e. they can solve the same kinds of problems even without the typical control structures like while and for (though sometimes can get very complicated)Recursion can sometimes be slowerEach recursive call is actually calling a function

  • Components of a recursionA recursion must haveOne or more ending caseSo the function will stopOne or more non-overlapping recursive case (current operation)So the function will call itself and you can calculate the correct answerChange of input towards the ending caseSo the ending case will be reached eventually

  • Building a recursionExample of writing a recursion (power)Ending case: when n=0 (or
  • Building a recursionGiven a sequence of numbers generated by the following formula:n0 = 1, n1 = 2nn = 3*nn-1 + 2*nn-2 + 1How to write a recursion to generate a number in the sequence given its position?Find out the base case(s)Find out the recursive case(s)Find out the change in each recursive cases

  • Building a recursionGiven a sequence of numbers generated by the following formula:n0 = 1, n1 = 2nn = 3*nn-1 + 2*nn-2 + 1Let k be the position number,Base cases:If k is 0, n is 1; if k is 1, n is 2Recursive cases:Value of n is the combination of the k-1th and k-2th numbersChange in recursive cases:To find out what the values of k-1th and k-2th numbers are

  • Building a recursionLet k be the position number,Base cases:If k is 0, n is 1; if k is 1, n is 2Recursive cases:Value of n is the combination of the k-1th and k-2th numbersChange in recursive cases:To find out what the values of k-1th and k-2th numbers areint genNum(int k) {if(k == 0) return 1;else if(k == 1) return 2;else return 3*genNum(k-1) + 2*genNum(k-2) + 1;}

  • Common mistakes with recursionEnding case may never be reachedint fac(int numb){ if(numb==1) return 1; else return numb*fac(numb-1);}int foo(int numb){ if(numb==1) return 1; else return numb*foo(numb+1);}Infinite recursion if numb < 1Infinite recursion if number > 1

  • Common mistakes with recursion Order of operations reversedDoes not reverse the print out of the valuevoid printReverse(int n) { if(n
  • Tracing a recursionTo trace a recursion (works like a stack)Suppose we have: power(2,3)k=2 n=3k=2 n=2k=2 n=1k=2 n=0n-1n-1n-11248

  • QuestionsWrite out a C++ recursive functionthat calculates factorial of a positive integerEnding case(s)?

    Recursive cases(s)?

    Change in recursive case(s)?

  • QuestionsWrite out a C++ recursive function that returns the n-th Fibonacci number Ending case(s)?

    Recursive cases(s)?

    Change in recursive case(s)?