磁盘调度算法c语言
时间: 2023-08-24 08:14:35 浏览: 46
磁盘调度算法是用来优化磁盘访问时间,常见的算法有FCFS、SSTF、SCAN、C-SCAN等。下面是一个使用C语言实现SCAN算法的示例代码:
```c
#include <stdio.h>
#include <stdlib.h>
#define MAX 1000
int queue[MAX];
int head, tail;
void initQueue() {
head = tail = 0;
}
int isQueueEmpty() {
return head == tail;
}
int isQueueFull() {
return (tail + 1) % MAX == head;
}
void enqueue(int value) {
if (isQueueFull()) {
printf("Queue is full\n");
exit(1);
}
queue[tail] = value;
tail = (tail + 1) % MAX;
}
int dequeue() {
if (isQueueEmpty()) {
printf("Queue is empty\n");
exit(1);
}
int value = queue[head];
head = (head + 1) % MAX;
return value;
}
void scan(int arr[], int n, int start) {
int i, pos, move = 0;
int left = start - 1, right = start + 1;
while (left >= 0 || right < n) {
if (left >= 0 && arr[left] >= 0) {
enqueue(arr[left]);
arr[left] = -1;
left--;
} else if (right < n && arr[right] >= 0) {
enqueue(arr[right]);
arr[right] = -1;
right++;
} else {
if (left >= 0) {
left--;
}
if (right < n) {
right++;
}
}
}
printf("Sequence of disk access:\n%d", start);
while (!isQueueEmpty()) {
pos = dequeue();
printf(" -> %d", pos);
move += abs(start - pos);
start = pos;
}
printf("\nTotal head movement: %d\n", move);
}
int main() {
int n, start, i;
int arr[MAX];
printf("Enter the number of disk requests: ");
scanf("%d", &n);
printf("Enter the disk requests: ");
for (i = 0; i < n; i++) {
scanf("%d", &arr[i]);
}
printf("Enter the starting position: ");
scanf("%d", &start);
initQueue();
scan(arr, n, start);
return 0;
}
```
该代码实现了SCAN算法,使用循环队列来存储待访问的磁道号,遍历磁道号数组,将其存储到队列中,然后按照磁头的移动顺序输出磁道号,并计算磁头的总移动距离。
相关推荐
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)