Outline for June 1, 2009
Reading
: §13.3
Guest Lecturer
: Justin Cummins
Recursive refresher: Fibonacci sequence
Merge function
Merges two sorted lists into a third sorted list
Compare first item of each list
Return the smaller value concatenated with the merge of the two lists (minus the smaller value)
If one list is empty, the result is the other list (terminating case/condition)
Linear time
O
(
n
): each compare places one item into the result, where the result has
n
items
Mergesort function (see
mergesort.py
)
One of the fastest general-purpose sorts
Divide-and-conquer algorithm
Parallelizes easily
Python’s list sort is a modified mergesort
Algorithm
Divide list in half
Recursively sort each half
Merge the sorted parts together
If a list has 0 or 1 element, it’s already sorted (terminating case/condition)
Example: Mergesort class volunteers by height
O
(
n
log
n
) algorithm in worst case and average case
Compare mergesort to selection sort on random list of integers
Selection sort is a quadratic,
O
(
n
2
), algorithm
For 10 and 100 elements, selection sort slightly faster
For 1000 elements, mergesort almost 10× faster
For 10000 elements, mergesort over 100× faster