The snippet below came from somewhere on the Internet that I haven't kept track of.
I wrote the snippet below, and it does the trick, but it may not be sufficient to make a generic color-sorting function. It also needs cleaning up.