I wrote a comparator for a custom class of mine and when I ran my code I realised the output of my list of these objects was in the reverse order as to what I wanted. It was ascending as opposed to descending. This was because I stuck to the spec of compare where a return value of less than 0 means the other object is less than this and so on.To fix this I called the reverse method on my list, but I could've also changed the compare method so that it returns greater than 0 where the other object is less than this.What is seen as the standard for this case and why?
Best practice to sort then reverse, or write backwards comparator?
language agnostic;coding standards;comparison
Start by ignoring any performance impact of reversing the list. Any sensible list-reversal will be linear in time, which means that for large lists, the sorting will dominate.If there is a natural ordering of your elements (i.e. an ordering which is independent from your particular implementation), I would recommend sort + reverse. This will make the comparator easier to reuse, and it will be easier to understand the code which invokes the sort. Compare these two:x = <array of integers>x.sort(NaturalOrdering)x.reverseandx = <array of integers>x.sort(MyOrdering) // what ordering is this?If there is no natural ordering (i.e. you are imposing an artificial ordering just to be able to sort elements), it probably makes more sense to have the comparator return the desired ordering directly.If you are tempted to start optimizing at this point, please measure the code before and after you optimize. It is never obvious which implementation is the faster one.