Fix sorting bug which could cause the algorithm to produce worse paths.