MCS 275 Spring 2021
Emily Dumas
Course bulletins:
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: reorder the elements of L
in place to achieve sorted order.
L
has 0 or 1 elements, it is already sorted. Do nothing.L
into a new list L1
, and the rest into L2
.L1
and L2
(in place).merge_sorted_lists
to merge L1
and L2
into L
.This algorithm depends on having a function merge_sorted_lists
that can merge to sorted lists into a single sorted list.
merge_sorted_lists
:
Input: sorted lists L1 and L2, and a list L
of the proper length in which to store the results.
Goal: copy all elements of L1
and L2
into L
in increasing order.
i1,i2,i
to keep track of current position in L1,L2,L
respectively. Set all to zero.i1 < len(L1)
and i2 < len(L2)
, do the following:
L1[i1]
and L2[i2]
is smaller.L[i]
.i1,i2
was used.i
L1
into L
.L2
into L
.Let's implement mergesort
in Python.
No changes to the references from Lecture 13