Make sorting more robust.

This fixes bug #1766.