使用一段java实现FCFS、SSTF、SCAN 和 C-SCAN 四种磁盘调度算法的模拟实现
时间: 2024-01-26 22:03:41 浏览: 90
以下是使用 Java 实现 FCFS、SSTF、SCAN 和 C-SCAN 四种磁盘调度算法的模拟实现:
```java
import java.util.*;
public class DiskScheduling {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("Enter the number of disk requests: ");
int n = sc.nextInt();
int[] requests = new int[n];
System.out.print("Enter the disk requests: ");
for (int i = 0; i < n; i++) {
requests[i] = sc.nextInt();
}
System.out.print("Enter the initial head position: ");
int head = sc.nextInt();
// FCFS algorithm
fcfs(requests, head);
// SSTF algorithm
sstf(requests, head);
// SCAN algorithm
scan(requests, head);
// C-SCAN algorithm
cscan(requests, head);
}
public static void fcfs(int[] requests, int head) {
int n = requests.length;
int total = 0;
for (int i = 0; i < n; i++) {
total += Math.abs(head - requests[i]);
head = requests[i];
}
System.out.println("FCFS algorithm total head movement: " + total);
}
public static void sstf(int[] requests, int head) {
int n = requests.length;
int total = 0;
boolean[] visited = new boolean[n];
Arrays.fill(visited, false);
for (int i = 0; i < n; i++) {
int index = -1;
int minDist = Integer.MAX_VALUE;
for (int j = 0; j < n; j++) {
if (!visited[j]) {
int dist = Math.abs(head - requests[j]);
if (dist < minDist) {
index = j;
minDist = dist;
}
}
}
visited[index] = true;
total += minDist;
head = requests[index];
}
System.out.println("SSTF algorithm total head movement: " + total);
}
public static void scan(int[] requests, int head) {
int n = requests.length;
int total = 0;
Arrays.sort(requests);
int index = Arrays.binarySearch(requests, head);
if (index < 0) {
index = -(index + 1);
}
for (int i = index; i < n; i++) {
total += Math.abs(head - requests[i]);
head = requests[i];
}
total += Math.abs(head - (n - 1));
head = n - 1;
for (int i = n - 2; i >= index; i--) {
total += Math.abs(head - requests[i]);
head = requests[i];
}
System.out.println("SCAN algorithm total head movement: " + total);
}
public static void cscan(int[] requests, int head) {
int n = requests.length;
int total = 0;
Arrays.sort(requests);
int index = Arrays.binarySearch(requests, head);
if (index < 0) {
index = -(index + 1);
}
for (int i = index; i < n; i++) {
total += Math.abs(head - requests[i]);
head = requests[i];
}
total += Math.abs(head - (n - 1)) + (n - 1);
head = 0;
for (int i = 0; i < index; i++) {
total += Math.abs(head - requests[i]);
head = requests[i];
}
System.out.println("C-SCAN algorithm total head movement: " + total);
}
}
```
使用示例:
```
Enter the number of disk requests: 8
Enter the disk requests: 98 183 37 122 14 124 65 67
Enter the initial head position: 53
FCFS algorithm total head movement: 640
SSTF algorithm total head movement: 236
SCAN algorithm total head movement: 208
C-SCAN algorithm total head movement: 236
```
阅读全文