It's not a short sample, but...
Apache::AutoIndex does this.
It uses Apache functions for gathering parameters and so on, but
wouldn't be hard to translate back to CGI.pm if you prefer.
The code for the sorting is in do_sort; it's not especially clever,
just uses a different sort call for each column selection.