磁盘调度算法Java代码
时间: 2023-07-05 18:24:14 浏览: 95
下面是一个简单的磁盘调度算法的Java代码,使用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 head position: ");
int head = sc.nextInt();
System.out.print("Enter the number of disk requests: ");
int n = sc.nextInt();
int[] requests = new int[n];
System.out.println("Enter the disk requests: ");
for (int i = 0; i < n; i++) {
requests[i] = sc.nextInt();
}
System.out.print("Enter the direction (L or R): ");
String dir = sc.next();
int[] sequence = new int[n + 1];
sequence[0] = head;
if (dir.equals("L")) {
Arrays.sort(requests);
int index = Arrays.binarySearch(requests, head);
if (index < 0) {
index = -index - 1;
}
for (int i = index - 1, j = 1; i >= 0; i--, j++) {
sequence[j] = requests[i];
}
for (int i = index, j = index + 1; i < n; i++, j++) {
sequence[j] = requests[i];
}
} else {
Arrays.sort(requests);
int index = Arrays.binarySearch(requests, head);
if (index < 0) {
index = -index - 1;
}
for (int i = index, j = 1; i < n; i++, j++) {
sequence[j] = requests[i];
}
for (int i = index - 1, j = index + 1; i >= 0; i--, j++) {
sequence[j] = requests[i];
}
}
System.out.println("The sequence of disk access is:");
for (int i = 0; i <= n; i++) {
System.out.print(sequence[i] + " ");
}
System.out.println();
}
}
```
这个程序实现了一个简单的磁盘调度算法,用户可以输入磁头的初始位置、磁盘请求的数量和请求的位置,以及磁头移动的方向(左或右)。程序使用SCAN算法,按照请求的位置排序,然后按照磁头移动的方向扫描磁盘,输出磁头访问的顺序。
阅读全文