Skip to main content

C'est la Z

Motivating and understanding quicksort

Thks question was posed the other day - how can one get students to truly understand the quicksort algorithm?

I've written a few posts about quicksort. The last time I did a lesson writeup on the subject I wrote about first looking and quickselect and then moving to the quicksort. The class was first faced with the problem of writing a routine to find the Kth smallest item in an unsorted data set. The first solution was n^2 and then refined to a quickselect. This led directly to the quicksort.

I liked the lesson and I think it worked well when I taught it but that was partly due to the overall tenor of that particular group of students.

A similar approach develops the quicksort in a similar way but is both more direct and accessible.

The motivating problem is to put one item in a data set in its proper place. You could select one person in class and arrange the class so that the selected student is in their proper size place, that is everyone shorter on one side, taller on the other. You could also do this for age. A similar exercise could be done with any number of manipulatives.

This operation of arranging the rest of the set around one selected item or person is very easy and in fact it's trivial to show that this can be done in linear time.

Once we've done this arrangement, we can discuss what we can infer from this new arrangement. We can now tell that:

  • everyone to the left of the "pivot" is less than the pivot
  • everyone to the right is greater
  • The pivot element is at its true location if the list were

sorted. That is, if we started arranging around item k, then we've moved item k to the kth location in the dataset.

From here it's a small jump to the quicksort algorithm, just repeat the process on the left and right data sets.

This approach not only makes the algorithm and its development clear and simple but it also can be used to illustrate the worst case n^2 behavior.

The whole thing, minus the coding, can also be done as an unplugged activity.

In case anyone's interested, I also wrote a post on subtle implementation errors when writing the quicksort (here) and also looking at the qucksort from the point of view of different programming paradigms (here).

Enjoy.

comments powered by Disqus