模擬最短尋道時間優先SSTF演算法
阿新 • • 發佈:2018-12-26
選擇這樣的程序,其要求訪問的磁軌與當前磁頭所在的磁軌距離最近,以使每次的尋道時間最短
#include <malloc.h>
#include<stdio.h>
#include<math.h>
#include <limits.h>
typedef struct track{
int column;
struct track *next;
}node;
int location; /*當前磁頭位置*/
int sum_move; /*磁頭移動總磁軌數*/
float ave_move; /*磁頭移動平均磁軌數*/
int direction; /*磁頭移動的方向:direction=1 表示從裡向外移動,direction=-1 表示從 外向裡移動*/
int found_node(node *head) /*找到離當前磁頭最近且與direction 同方向的磁軌*/
{
node *p,*t;
int panduan,truecol=0,jiange=10000;
p=head;
t=head;
while(p&&t){
if(direction==1){
while(p){
if(p->column>=location)
{
panduan=p->column-location;
if (panduan<jiange)
{
truecol=p->column;
jiange=panduan;
}
}
p=p->next;
}
if(truecol==0){
direction=-1;
}
}
if(direction==-1){
while(t){
if (t->column<location)
{
panduan=location-t->column;
if(panduan<jiange)
{
truecol=t->column;
jiange=panduan;
}
}
t=t->next;
}
if(truecol==0){
direction=1;
}
}
}
sum_move+=jiange;
location=truecol;
printf("%d ",truecol);
return truecol;
}
node *SCAN(node *head) /*調用found_node 找到滿足條件的磁軌,並從head 連結串列中刪除該結點*/
{
node *pre,*p;
int a;
a=found_node(head);
pre=NULL;
p=head;
while(p&&(p->column!=a)){
pre=p;
p=p->next;
}
if(p){
if(!pre) {head=head->next;}
else pre->next=p->next;
}
return head;
}
void main()
{
int i,num,disk_length;
node *head,*p1,*p2;
head=NULL;
printf("輸入磁碟柱面總數:\n");
scanf("%d",&disk_length);
printf("輸入磁碟讀寫請求總數:\n");
scanf("%d",&num);
printf("輸入磁碟讀寫請求柱面號序列:\n");
for(i=1;i<=num;i++)
{
p1=(node *)malloc(sizeof(node));
scanf("%d",&p1->column);
if(head==NULL){
head=p1;
p2=p1;
}
else{
p2->next=p1;
p2=p1;
}
p2->next=NULL;
}
printf("輸入磁碟當前位置為:\n");
scanf("%d",&location);
printf("輸入磁碟移動方向(1 表示從裡向外移動,-1 表示從外向裡移動):\n");
scanf("%d",&direction);
printf("\n依次訪問的柱面號為:\n");
sum_move=0;
for(i=1;i<=num;i++)
{
SCAN(head);
}
ave_move=(float)sum_move/num;
printf("\n總的移動柱面次數為:%d\n",sum_move);
printf("\n平均移動次數為:%.2f\n",ave_move);
}