MCS 275 Spring 2021
Emily Dumas
Course bulletins:
Python lists have built-in .sort()
method. Why talk about sorting?
Last time we discussed and implemented mergesort.
History: Developed by von Neumann (1945) and Goldstine (1947).
But is it a good way to sort a list?
Theorem: If you measure the time cost of mergesort in any of these terms
L[i] = x
counts as 1)then the cost to sort a list of length $n$ is less than $C n \log(n)$, for some constant $C$ that only depends on which expense measure you chose.
$C n \log(n)$ is pretty efficient for an operation that needs to look at all $n$ elements. It's not linear in $n$, but it only grows a little faster than linear functions.
Furthermore, $C n \log(n)$ is the best possible time for comparison sort of $n$ elements (though different methods might have better $C$).
Another comparison sort typically implemented using recursion. Developed by Hoare, 1959.
Unlike mergesort, it uses very little temporary storage, and only ever swaps pairs of elements.
Starting with an unsorted list:
It's divide and conquer, but with no merge step. The hard work is instead in partitioning.
For the moment, we'll take the partition step as a "black box", assuming we already have:
def partition(L,start,end):
"""Look at L[start:end]. Take the last element as a pivot.
Move elements around so that any value less than the pivot
appears before it, and any element greater than or equal to
the pivot appears after it. L is modified in place. The
final location of the pivot is returned."""
# TODO: Add code here
Note this function uses the last element as a pivot. Later we'll discuss other options.
Let's implement quicksort
in Python.
quicksort
:
Input: list L
and indices start
and end
.
Goal: reorder elements of L
so that L[start:end]
is sorted.
(end-start)
is less than or equal to 1, return immediately.partition(L)
to partition the list, letting m
be the final location of the pivot.
quicksort(L,start,m)
and quicksort(L,m+1,end)
to sort the parts of the list on either side of the pivot.How to write partition(L,start,end)
?
Recall we plan to make a version that uses the last element of L[start:end]
as the pivot.