# 13. Recursion and Sorting

#### Thursday October 15, 1998

[Previous Lecture] [Next Lecture]

Assigned Reading:  online notes on sorting part 1 and part 2

Handouts (available on-line): Project 3

Programs from this lecture: on recursion and on sorting.

Topics Covered:

• More recursion: You should practice writing simple recursive functions. Get used to arguing that the base case is correct. Get used to arguing that the recursive case is correct. Don't get too cute with the base case. It doesn't hurt to have some extra cases even if they don't get used!

• Last time, we started developing a recursive function that determines whether the sum of the integers in an array is even. Here's the final version.

• Next topic: How do we go about writing recursive functions? We can practice on some simple examples. Here are three ways to use recursion to add the numbers in an array:

• Method 1: break off the last element of the array and recursively sum the first part of the array.

• Method 2: break off the first element of the array and recursively sum the last part of the array.

• Method 3: divide the array into two halves and recursively sum the two halves.

The sample runs show that the 3 methods yield the same results.

• Long discussion about Project 3.

• Start section on sorting.

• First we noted how to use the assert() macro to help debugging.
Program and sample run.

• We defined a C++ Array class to help us test our sorting algorithms. Note how the constructor uses the random number generator functions srand48() and drand48().