MCS 275 Spring 2022
Emily Dumas
Course bulletins:
You will write functions (mostly recursive) to enumerate integer splittings.
E.g. 1+2+3
and 3+1+2
and 4+2
are splittings of 6
A strategy that often involves recursion.
Not always possible or a good idea. It only works if merging partial solutions is easier than solving the entire problem.
Suppose you have a list of objects that can be compared with ==
, >
, <
.
You'd like to reorder them in increasing order.
This problem is called comparison sort. There are many solutions.
A divide-and-conquer solution to comparison sort.
It is a fast solution, often used in practice.
Key: It is pretty easy to take two sorted lists and merge them into a single sorted list.
So, let's divide our list into halves, sort each one (recursively), then merge them.
Now we'll formalize this.
mergesort
:
Input: list L
whose elements support comparison.
Goal: return a list that contains the items from L
but in sorted order.
L
has 0 or 1 elements, return L
L
into rougly equal pieces L0
and L1
.
L0
and L1
.merge
to merge these sorted lists and return the result.This algorithm depends on having a function merge
that can merge two sorted lists into a single sorted list.
merge
:
Input: sorted lists L0
and L1
.
Goal: return a sorted list with same items as L0+L1
L
i0,i1
to keep track of current position in L0,L1
respectively. Set to zero.i0 < len(L0)
and i1 < len(L1)
, do the following:
L0[i0]
and L1[i1]
is smaller.L
.
i0,i1
was used.L0
to L
.L1
to L
.Let's implement mergesort
in Python.