Adding some logic to sort for a (hopfully) better algorithm.