First, neither of those compareTo methods are (completely) correct:
public int compareTo(Job t) {
int compare = ((Job) t).time;
return this.time - compare;
}
If the time
values can be negative, then the subtraction can overflow resulting in a number with the wrong sign.
public int compareTo(Job t) {
return new Integer(getTime()).compareTo((t.getTime()));
}
It is unnecessary (and wasteful) create and Integer
instance. Use the static Integer.compare(int, int)
method instead.
But neither of those issues explain the results you are seeing.
My guess is that the real problem is simply that length - 1
is incorrect.
According to the javadoc, the 3rd parameter of the Array.sort(...)
methods is an exclusive bound. If length
really represents the length of Q
... or the number of entries in Q
that are valid ... then you should use length
as the 3rd argument.
(The clue is that it is only the last element that is incorrectly sorted in your examples.)