Update: In fact, the only acceptable solution for this problem would be sorting the array ascending and then reversing it.
Let S be the following sequence of events:
Event | Time A | 0:00 B | 0:01 C | 0:01 D | 0:02
I have a simple Comparator to sort S, which sorts the elements according to the time value.
public int compare(Event e1, Event e2) { // Reverse sorting. // _sortOrder is set outside this method. if(SORT_DESCENDING.equals(_sortOrder)) return e2.getTime() - e1.getTime(); /* time is long */ return e1.getTime() - e2.getTime(); }
The problem is: when the sort order is ascending, S is sorted correctly: A, B, C, D.
But when I use reverse sorting, S becomes D, B, C, A:
Event | Time D | 0:02 B | 0:01 /* B and C should be reversed */ C | 0:01 A | 0:00
This happens because the default sorting algorithm keeps the original order for elements with the same time value.
So, how do I sort it reverse without keeping the original order?
Note: I know I can sort S ascending and further simply revert it, but unfortunately this is not an option in my case.
The sorting algorithm is correct: 0.01 is 0.01. Unless there’s something you’re not telling us. If however you want the exact reverse order of an ascending sort then sort them in ascending order and use Collections.reverse(). By this I mean:
which will give you exactly what you want.
But if reversing isn’t an option you only have two options left:
Now before you say you can’t reverse (why?), let me ask you how you’re sorting? if you’re using
Collections.sort()consider the source code (Java 6u10):So it copies the collection into an array, sorts that array and then uses that to reorder the collection.
Are you sure you can’t afford a reversal?