Fix multiple sort criteria

With larger datasets, the sorting was incorrect. Now, instead of
sorting the array multiple times, multiple criteria are considered
in a single pass.
Some formatting
Fixed sort bug