Sunday, March 14, 2010

Sorting from the top and from the bottom

I've been meaning to write this post for a couple of weeks, but some
times life just gets in the way.

I've always thought it important to arm students with as many
different tools with which to attack problems as possible. As such,
the courses I teach use a number of different languages, each
highlighting a different paradigm and thought process. The hope is
that by the end of the sequence, they can look at problems from many
different angles.

In my advanced placement classes, we recently studied sorting
algorithms. It think the quicksort is a good example of a problem
that can be looked at from multiple points of view.

In my experiences talking to teachers and students who cut there teeth
using languages like Java, C, or C++, much of the discussion deals with
the actual partitioning of the array. Comparing elements, swapping
them and arriving in the middle. One might end up with something like
this as a first cut:

A fair amount of time and detail is spent dealing with the low level
movement of data within the array . This is important – good stuff,
but it takes the emphasis away from the higher level elegance of the
algorithm.

The quicksort can be described as:

If the size of the list is <= 1, return.

Select a pivot element

Generate the list L of items smaller than the pivot

Generate the list H of items larger than the pivot

the sorted list is qsort(L)+pivot+qsort(R)

Having seen some scheme in their intro class, our students have a tool
with which we can describe the quicksort in terms much closer to the
description (allowing for the fact that this doesn't deal with
multiple values equal to the pivot correctly):

This allows us to discuss the quicksort at a much higher level and
focus on things like selecting a good pivot or the analysis of the run
time. I believe this makes it much easier to really understand what's
going on.

Having discussed it in this functional context, we can also look at
the same thing in a scripting language such as python:

Again, the focus is on the algorithm, not the array or list
manipulation.

Looking at the problem from both the more abstract side, which in this
case functional languages allow, and the more concrete, as we did in
Java gives our students more tools with which to attack problems.