6. Algorithms - Extra-Recursion

Embed Size (px)

Citation preview

  • 8/12/2019 6. Algorithms - Extra-Recursion

    1/23

    Recursion

    Programming technique in which a

    method (function) calls itself

  • 8/12/2019 6. Algorithms - Extra-Recursion

    2/23

    Triangular Numbers

    What isx in the series?

    1, 3, 6, 10, 15, 21,x

    Also called triangular numbers

    #1 = 1 #2 = 3 #3 = 6 #4 = 10

    and so on

  • 8/12/2019 6. Algorithms - Extra-Recursion

    3/23

  • 8/12/2019 6. Algorithms - Extra-Recursion

    4/23

    Triangular Numbers

    You might decide that the value of any term

    can be obtained by adding up all the vertical

    columns of squares

    4 + 3 + 2 + 1 = 10

  • 8/12/2019 6. Algorithms - Extra-Recursion

    5/23

    Procedural Programming

    int triangle(int n)

    {

    int total = 0

    while(n > 0) // until n is 1

    {

    total = total + n; // add n (column height) to total

    --n; // decrement column height

    }

    return total}

  • 8/12/2019 6. Algorithms - Extra-Recursion

    6/23

    Recursive Programming

    The value of the n-th term can be thought

    of as the sum of only 2 things, instead of a

    whole series. These are:1. The first (tallest) column, which has the value n

    2. The sum of all the remaining columns

    4 + 6 in the remaining columns = 10

  • 8/12/2019 6. Algorithms - Extra-Recursion

    7/23

    Recursive Programming

    int triangle (int n)

    {

    return (n + sumRemainingColumns(n));

    }

    If we knew a method that found the sum of

    all remaining columns:

  • 8/12/2019 6. Algorithms - Extra-Recursion

    8/23

    Recursive Programming

    int triangle (int n)

    {return (n + SumAllColumns(n-1));

    }

    sumRemainingColumns (n) = sumAllColumns(n-1)

  • 8/12/2019 6. Algorithms - Extra-Recursion

    9/23

  • 8/12/2019 6. Algorithms - Extra-Recursion

    10/23

    Recursion : Passing the Buck

    Someone tells me to find the 4thtriangular number

    I know this is 4 plus the 3rdtriangular number

    I call Harry and ask him to find the 3rdtriangular number

    Harry knows that the 3rdtriangular number is 3 plus the 2ndtriangular number

    Harry calls Jane and asks her to find the 2ndtriangular number

    Jane knows that the 2ndtriangular number is 2 plus the 1st

    triangular number (which is 1) The buck-passing must end at some point. Otherwise, the

    method would call itself over and over in an infinite series thatwould paralyse the program

  • 8/12/2019 6. Algorithms - Extra-Recursion

    11/23

    The Buck Stops Here

    The person who is asked to find the 1sttriangular number

    (when n = 1), must know the answer without asking

    anyone else. He knows the answer is 1.

    Every recursive method must have a base case to prevent

    infinite recursion

    int triangle (int n)

    { if(n == 1) // base case

    return 1;

    else

    return (n + triangle(n-1));

    }

  • 8/12/2019 6. Algorithms - Extra-Recursion

    12/23

    Trace the output of the following program

    int triangle (int n)

    {

    System.out.println (Entering: n= + n);

    if(n == 1) {

    System.out.println (Returning 1);return 1;

    }

    else {

    int temp = n + triangle(n-1);

    System.out.println(Returning + temp);return temp

    }

    }

  • 8/12/2019 6. Algorithms - Extra-Recursion

    13/23

    Whats really happening?

    Each time the triangle( ) method calls itself, its argument,which starts at 4, is reduced by 1.

    The method plunges down into itself again again until its

    argument is reduced to 1. Then it returns. This triggers an entire series of returns.

    The method rises back up, phoenix-like, out of thediscarded versions of itself.

    Each time it returns it adds the value of nit was called with

    to the return value from the method it called. Note: Just before the innermost version returns a 1, there

    are actually 4 different incarnations of triangle( ) inexistence at the same time.

  • 8/12/2019 6. Algorithms - Extra-Recursion

    14/23

    Characteristics of recursive methods

    It calls itself

    When it calls itself, it does so to solve a smaller problem

    Theres some version of the problem that is simple enoughthat the routine can solve it, and return, without calling

    itself.

    int triangle (int n)

    {

    if(n == 1) // base casereturn 1;

    else

    return (n + triangle(n-1));

    }

  • 8/12/2019 6. Algorithms - Extra-Recursion

    15/23

    Is recursion efficient?

    Method calling involves some overhead

    Control must be transferred to and fro, with each callhaving its own set of argumentsutilising a stack so that

    the method can access the argument values and knowwhere to return

    Memory usage may cause stack overflow

    Recursive computer programs require more memory andcomputation compared with iterative algorithms, but they

    are simpler and for many cases a natural way of thinkingabout the problem.

    Recursion is usually used because itsimplifies a problemconceptually, not because its inherently more efficient

  • 8/12/2019 6. Algorithms - Extra-Recursion

    16/23

  • 8/12/2019 6. Algorithms - Extra-Recursion

    17/23

    Factorials

    int factorial (int n)

    {

    if(n == 0) // base case

    return 1;else

    return (n * factorial(n-1));

    }

  • 8/12/2019 6. Algorithms - Extra-Recursion

    18/23

    Find the n-th even number

    Procedural Method

  • 8/12/2019 6. Algorithms - Extra-Recursion

    19/23

    Algorithm -> Even(positive integer k)Input: k, a positive integerOutput: k-th even natural number (the first even being 0)

    Algorithm:int i, even;i:= 1;even:= 0;while( i < k) {

    even:= even+ 2;

    i:= i+ 1;}return even.

    Recursive Algorithm

  • 8/12/2019 6. Algorithms - Extra-Recursion

    20/23

  • 8/12/2019 6. Algorithms - Extra-Recursion

    21/23

    Recursive Binary Searchpublic int find(double searchKey)

    {

    return recFind(searchKey, 0, nElems-1);

    }//-----------------------------------------------------------

    private int recFind(double searchKey, int lowerBound,

    int upperBound)

    {

    int curIn;

    curIn = (lowerBound + upperBound ) / 2;

    if(a[curIn]==searchKey)

    return curIn; // found it

    else if(lowerBound > upperBound)

    return nElems; // can't find it

    else // divide range

    {if(a[curIn] < searchKey) // it's in upper half

    return recFind(searchKey, curIn+1, upperBound);

    else // it's in lower half

    return recFind(searchKey, lowerBound, curIn-1);

    } // end else divide range

    } // end recFind()

  • 8/12/2019 6. Algorithms - Extra-Recursion

    22/23

    Partition Algorithm

  • 8/12/2019 6. Algorithms - Extra-Recursion

    23/23

    Partition Algorithmpublic int partitionIt(int left, int right, double pivot)

    {

    int leftPtr = left - 1; // right of first elemint rightPtr = right + 1; // left of pivot

    while(true)

    {

    while(leftPtr < right && // find bigger item

    theArray[++leftPtr] < pivot)

    ; // (nop)

    while(rightPtr > left && // find smaller item

    theArray[--rightPtr] > pivot)

    ; // (nop)

    if(leftPtr >= rightPtr) // if pointers cross,

    break; // partition done

    else // not crossed, soswap(leftPtr, rightPtr); // swap elements

    } // end while(true)

    return leftPtr; // return partition

    } // end partitionIt()