UMBC CMSC202, Computer Science II, Fall 1998,
Sections 0101, 0102, 0103, 0104
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().
Header file and
implementation.
- First sorting algorithm: selection sort. Selection Sort
repeatedly looks for the ith smallest element in the array and
places it in the correct position. Our function for Selection Sort
is implemented in a separate file ssort.C. The header file
sorts.h declares all the
sorting functions we will be using. A separate main program tests the Selection
Sort function. We use the UNIX time command to measure the
performance of the Selection Sort algorithm. The sample runs show that each time
we double the size of the array to be sorted, the running time of
the Selection Sort function increases by a factor of 4.
- Selection Sort is slow. It took 6.96 hours to sort an array of
320,000 floating point numbers.
Next time, we will see how sorting
algorithms developed using the recursive "divide and conquer" strategy are
much faster than Selection Sort
[Previous Lecture]
[Next Lecture]
Last Modified:
22 Jul 2024 11:28:50 EDT
by
Richard Chang
Back up
to Fall 1998 CMSC 202 Section Homepage