用磁盘调度算法编写代码要求分别FCFS、SSTF、SCAN、C-SCAN
时间: 2023-10-06 18:04:41 浏览: 128
[操作系统磁盘调度算法]OS实验C语言代码实现FCFS/SSTF/SCAN/CSCAN
5星 · 资源好评率100%
以下是四种磁盘调度算法的代码实现:
1. FCFS(先来先服务)
```python
def fcfs(current, requests):
total_distance = 0
for request in requests:
total_distance += abs(request - current)
current = request
return total_distance
```
2. SSTF(最短寻道时间优先)
```python
def sstf(current, requests):
total_distance = 0
while requests:
shortest_distance = float('inf')
shortest_index = None
for i, request in enumerate(requests):
distance = abs(request - current)
if distance < shortest_distance:
shortest_distance = distance
shortest_index = i
request = requests.pop(shortest_index)
total_distance += shortest_distance
current = request
return total_distance
```
3. SCAN(扫描算法)
```python
def scan(current, requests, direction='right'):
total_distance = 0
if direction == 'right':
sorted_requests = sorted(requests)
else:
sorted_requests = sorted(requests, reverse=True)
index = 0
while index < len(sorted_requests) and sorted_requests[index] < current:
index += 1
while index < len(sorted_requests):
request = sorted_requests[index]
total_distance += abs(request - current)
current = request
index += 1
if direction == 'right':
total_distance += abs(current - max(requests))
current = max(requests)
else:
total_distance += abs(current - min(requests))
current = min(requests)
index -= 1
while index >= 0:
request = sorted_requests[index]
total_distance += abs(request - current)
current = request
index -= 1
return total_distance
```
4. C-SCAN(循环扫描算法)
```python
def c_scan(current, requests, direction='right'):
total_distance = 0
if direction == 'right':
sorted_requests = sorted(requests)
else:
sorted_requests = sorted(requests, reverse=True)
index = 0
while index < len(sorted_requests) and sorted_requests[index] < current:
index += 1
while index < len(sorted_requests):
request = sorted_requests[index]
total_distance += abs(request - current)
current = request
index += 1
if direction == 'right':
total_distance += abs(current - max(requests))
current = max(requests)
index = 0
else:
total_distance += abs(current - min(requests))
current = min(requests)
index = len(sorted_requests) - 1
while index >= 0:
request = sorted_requests[index]
total_distance += abs(request - current)
current = request
index -= 1
if direction == 'right':
total_distance += abs(current - min(requests))
else:
total_distance += abs(current - max(requests))
return total_distance
```
以上四种算法的实现均接收当前磁头位置和请求序列作为输入,返回总的寻道距离。其中 SCAN 和 C-SCAN 还接收运动方向参数,可以选择从内向外或从外向内扫描。
阅读全文