SUNY Geneseo Department of Computer Science


Recursion, Part 2

{Date}

CSci 141, Spring 2005
Prof. Doug Baldwin

Return to List of Lectures

Previous Lecture


Questions?

Structure of Recursive Algorithms

[Recursive Case, Base Case, and Test to Distinguish Them]

Designing Recursive Algorithms

Sections 6.2 and 6.3

Recursive probelm has to get smaller

Recursive algorithms can call other recursive algorithms

        a1()
            ... a2() ...
        a2()
            ... a1() ...

Possible problems

Value producing recursions

Design a recursive algorithm that counts the number of times a character, c, occurs in a string

    int countOccurrences( char c, String str )
        if str == ""
            return 0
        else if first char of str == c
            return 1 + countOccurrences(c,str.substring(1))
        else
            return 0 + countOccurrences(c,str.substring(1))
    global count
    int countOccurrences( char c, String str )
        if str == ""
            return count
        else if first char of str == c
            count = count + 1
            return countOccurrences(c,str.substring(1))
        else
            return countOccurrences(c,str.substring(1))

Search an array indexed 0 to n for a value x, return true or false

    bool search( array A, int n, x )
        if n < 0
            return false
        else
            return    A[n] == x
                   or search( A, n-1, x )

Search a sorted array (increasing order) A, between positions low and high, for x

[Narrow X's Position by Comparing to the Middle of a Range]

    bool binSearch( A, low, high, x )
        if ...
            ... middle ... / 2

Next

More advanced recursion

Read Sections 6.4 and 6.5


Next Lecture