Correct sort stability and improve performance.

This change also adds the debugmode command that enables timing of the
rebuild stages and shows this information in a message.