In Class: Week 10, recursion
Create a week10 subdirectory
in your cs21/class directory and copy over my starting point files:
$ cd
$ cd cs21/class
$ pwd
/home/your_user_name/cs21/class
$ mkdir week10
$ cd week10
$ pwd
/home/your_user_name/cs21/class/week10
$ cp ~turnbull/public/cs21/week10/* .
$ ls
list_recursion.py mergesort.py factorial.py
- Open factorial.py. We are going to write some iterative and
recursive versions of the same function. Iterative versions use
loops, recursive versions do not use loops, and instead contain
calls to themselves. The idea of recursive functions is based on
recursive definitions. For example, n! can be defined
as n(n-1)!.
- Lets try writing recursive factorial together
- Now you can try writing an iterative version of
a function (using a loop) that takes a positive int
value, n, and returns the sum of the first n integers.
- Next, try writing a recursive version of the sum of n ints
function.
- Open list_recursion.py. We are going to write some iterative and
and recursive functions that operate on lists.
- Next, open mergesort.py. Merge sort is a faster sorting algorithm
than selection sort. It uses the same type of divide and conquer
strategy as binary search does. It is also an example of an
elegant recursive solution.
We are going to look at the mergeSort code together. Once we
understand how the recursive calls work, you are going to come
up with an algorithm for merging two sorted lists of size n
into a sorted list of size 2n. Your merging algorithm should
be iterative (not recursive). Once you have an algorithm,
try coding it up in the merge function.