doctype html>
MCS 275 Spring 2024
Emily Dumas
Reminders and announcements:
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.
Problem: A list of length n
is given. For any two elements you are allowed to ask which one is "smaller". Using this information, put the list in increasing order.
A divide-and-conquer solution to comparison sort.
Fast, often used in practice.
Key: Two sorted lists can be easily merged into one sorted list.
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
.
mergesort
on 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.