我正在尝试制作一个自定义比较器,它将按照 C-LOOK 磁盘算法执行的顺序对整数数组进行排序。
我已将磁盘队列实现为 PriorityQueue,客户比较器将分配给磁盘队列列表。
我正在跟踪头部位置,并在比较方法中使用它,但它不太正确。
添加到队列中的前 5 个操作是 [32, 188, 36, 61, 97]。 头部位置从 50 开始。 但是排序后的前5个操作结果是[32, 36, 188, 97, 61]。
我还应该做什么?
private Comparator<Integer> CLOOK() {
return new Comparator<Integer>() {
@Override
public int compare(Integer o1, Integer o2) {
if (o1 < o2) {
if (o1 > currentHeadPosition) {
return 1;
}
return -1;
}
else if (o1 > o2) {
if (o2 > currentHeadPosition) {
return -1;
}
return 1;
}
else {
return 0;
}
}
};
}
// End CLOOK Comparator
最佳答案
哇,用 eclipse 调试器做了更多测试,我自己找到了解决方案。
private Comparator<Integer> CLOOK() {
return new Comparator<Integer>() {
@Override
public int compare(Integer o1, Integer o2) {
if (Math.abs(currentHeadPosition - o1) < Math.abs(currentHeadPosition - o2)) {
if (o1 < currentHeadPosition) {
return 1;
}
return -1;
}
else if (Math.abs(currentHeadPosition - o1) > Math.abs(currentHeadPosition - o2)) {
if (o2 < currentHeadPosition) {
return -1;
}
return 1;
}
else {
return 0;
}
}
};
}
// End CLOOK Comparator
关于Java比较方法为Circular Look磁盘算法对数组进行排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30065417/