Working on a SSTF algorithm using java.util.Comparator
This is what i have so far:
private int nextHeadPosition;
public SSTF(int currentHeadPosition) {
nextHeadPosition = currentHeadPosition;
}
@Override
public int compare(DiskRequest r1, DiskRequest r2) {
if (nextHeadPosition - r1.getTrackNumber() < nextHeadPosition - r2.getTrackNumber()) {
nextHeadPosition = r1.getTrackNumber();
return -1;
} else if (nextHeadPosition - r1.getTrackNumber() > nextHeadPosition - r2.getTrackNumber()) {
nextHeadPosition = r2.getTrackNumber();
return 1;
} else {
return 0;
}
}
with an initial head position of 50 it is producing this order:
[100, 99, 50, 45, 44, 1]
The output I am trying to produce:
[50, 45, 44, 1, 99, 100]
this might not be posible with comparator
edit
SSTF
for a queue of requests that have track numbers, the first request to be serviced will be the track that is closest to the current position of the head. Each subsequent request will be ordered by least distance from the position of the last request.
so for a queue with tracks [100, 99, 50, 45, 44, 1] and a current head position of 50, the first request will be 50. The next will be the track closest to 50, which is 45 in this case. lather rinse repeat.
解决方案
First, you want to compare the distance between the track and the head position, so you have to use the absolute value in your conditions.
if (Math.abs(nextHeadPosition - r1.getTrackNumber()) < Math.abs(nextHeadPosition - r2.getTrackNumber()))
But your compare method modifies the object, which is not a good idea since you don't know how Collections.sort() (I guess that's what you're trying to use) will use it. You have to write your own sorting algorithm I think.