写出FCFS SSTF SCAN CSCAN java代码
时间: 2023-07-26 15:04:46 浏览: 76
磁盘调度算法Java版(FCFS,SSTF,SCAN)
5星 · 资源好评率100%
以下是FCFS、SSTF、SCAN、CSCAN算法的Java实现示例:
FCFS:
```java
public static int FCFS(int[] requests, int head) {
int total = 0;
int cur = head;
for (int i = 0; i < requests.length; i++) {
total += Math.abs(cur - requests[i]);
cur = requests[i];
}
return total;
}
```
SSTF:
```java
public static int SSTF(int[] requests, int head) {
int total = 0;
int cur = head;
boolean[] visited = new boolean[requests.length];
Arrays.fill(visited, false);
for (int i = 0; i < requests.length; i++) {
int minDist = Integer.MAX_VALUE;
int index = -1;
for (int j = 0; j < requests.length; j++) {
if (!visited[j]) {
int dist = Math.abs(cur - requests[j]);
if (dist < minDist) {
minDist = dist;
index = j;
}
}
}
visited[index] = true;
total += minDist;
cur = requests[index];
}
return total;
}
```
SCAN:
```java
public static int SCAN(int[] requests, int head, int max) {
int total = 0;
int cur = head;
boolean left = true;
Arrays.sort(requests);
int index = Arrays.binarySearch(requests, cur);
if (index < 0) {
index = -index - 1;
}
while (index < requests.length && requests[index] <= cur) {
index++;
}
if (index == requests.length) {
left = false;
index--;
}
while (true) {
if (left) {
total += cur;
if (index == 0) {
total += requests[index];
cur = requests[index];
left = false;
index++;
} else {
total += cur - requests[index - 1];
cur = requests[index - 1];
index--;
}
} else {
total += max - cur;
if (index == requests.length - 1) {
total += max - requests[index];
cur = requests[index];
left = true;
index--;
} else {
total += requests[index + 1] - cur;
cur = requests[index + 1];
index++;
}
}
if (index < 0 || index >= requests.length) {
break;
}
}
return total;
}
```
CSCAN:
```java
public static int CSCAN(int[] requests, int head, int max) {
int total = 0;
int cur = head;
boolean left = true;
Arrays.sort(requests);
int index = Arrays.binarySearch(requests, cur);
if (index < 0) {
index = -index - 1;
}
while (index < requests.length && requests[index] <= cur) {
index++;
}
if (index == requests.length) {
index = 0;
}
while (true) {
if (left) {
total += cur;
if (index == requests.length) {
total += max - cur;
cur = 0;
index = 0;
} else {
total += cur - requests[index - 1];
cur = requests[index - 1];
}
left = false;
} else {
total += max - cur;
if (index == 0) {
total += max - requests[requests.length - 1];
cur = max;
index = requests.length;
} else {
total += requests[index] - cur;
cur = requests[index];
}
left = true;
}
if (index == requests.length && !left) {
break;
}
}
return total;
}
```
阅读全文